0
votes

I wrote this code to take input from the command line, and depending on the input, will perform a set of actions, or if the input is incorrect, throws an error. However, I also need to check if no arguments are supplied, which I try to account for in my else statement.

if(strcmp(argv[1], "-L") == 0) 
{
    //does stuff
}


else if(strcmp(argv[1], "-W") == 0)
{

    //does stuff

}

else if (*(argv[1]) != 1)
{
    puts("error: invalid input");
}

else //should check if no arguments
{
    puts("error: expected command line argument");
    return 1;
}

I am getting a segmentation fault whenever there are no arguments from the command line, and I'm not sure how to fix it. I have also tried to write the else statement this way:

else if(argc < 2)
{
    puts("error: expected command line argument");
    return 1;
}

This was based on my previous research on here where I found "C produce error if no argument is given in command line," but it won't work either. I am a beginner in C and do not fully understand argc and argv, so if anyone has any suggestions or logic I'm completely overlooking, please let me know.

2
Consider learning about the getopt function, a standard library call that makes it easy to handle command line options in a standard fashion. - larsks
Clearly you should be checking to see how many arguments you receive before you start using those arguments and not after, right? - Ken White
@KenWhite That would make sense, thanks! - Emma Barrett

2 Answers

2
votes

You need to check if argc < 2 before anything else.

Else you get segmentation fault because argv[index] could be something you have not privileges to access.

0
votes

Whatever you do, make sure you never try to access an index of argv that is greater or equal to argc. In your case, you are accessing index 1 when the last available index is 0 (argc is 1), that's why the segmentation fault. See this post for more info: What does int argc, char *argv[] mean?