Home > Software design >  'Segmentation fault' as user doesn't has an input
'Segmentation fault' as user doesn't has an input

Time:11-17

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.

$ ./rna
Segmentation fault

CodePudding user response:

Your checking the length (argc) of argv after accessing the element that does not exist. You cannot do strlen(argv[1]) before you're sure there is an argv[1]!

CodePudding user response:

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;
  •  Tags:  
  • c
  • Related