Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

'Segmentation fault' fault as user doesn't has an input

I wanted to implement a program that changes the user his DNA-string to a RNA-string. But I have some problems with my code that I don’t really understand. My code:

#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main(int argc, string argv[])

{
    int n = strlen(argv[1]);

    if (argc != 2)
    {
        printf("Usage: ./rna ATGC\n");
        return 1;
    }
    else if (argc == 2 && n >= 4)
    {
        for (int i = 0; i < n; i++)
        {
            if (argv[1][i] == 'A' || argv[1][i] == 'a')
            {
                printf("U");
            }
            else if (argv[1][i] == 'G' || argv[1][i] == 'g')
            {
                printf("C");
            }
            else if (argv[1][i] == 'C' || argv[1][i] == 'c')
            {
                printf("G");
            }
            else if (argv[1][i] == 'T' || argv[1][i] == 't')
            {
                printf("A");
            }
        }
    return 0;
    }
    if (n <= 3)
    {
        printf("Invalid DNA\n");
    }

}

If the user just runs the program I want to get an output like this:

$ ./rna
Usage: ./rna ATGC

But, I get this and can’t really figure out what is wrong.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$ ./rna
Segmentation fault

>Solution :

int n = strlen(argv[1]);

if there are no command-line arguments it invokes undefined behaviour.

change to:

size_t n = argc > 1 ? strlen(argv[1]) : 0;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading