0

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.

chrk
  • 4,037
  • 2
  • 39
  • 47
Emma Barrett
  • 83
  • 1
  • 10
  • 2
    Consider learning about the [getopt](https://www.gnu.org/software/libc/manual/html_node/Example-of-Getopt.html) function, a standard library call that makes it easy to handle command line options in a standard fashion. – larsks Oct 28 '16 at 02:16
  • Possible duplicate of [What are the arguments to main() for?](http://stackoverflow.com/questions/3734111/what-are-the-arguments-to-main-for) – Ken White Oct 28 '16 at 02:17
  • 1
    Clearly you should be checking to see how many arguments you receive **before** you start using those arguments and not **after**, right? – Ken White Oct 28 '16 at 02:18
  • @KenWhite That would make sense, thanks! – Emma Barrett Oct 28 '16 at 02:19

2 Answers2

2

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.

chrk
  • 4,037
  • 2
  • 39
  • 47
elikatsis
  • 479
  • 1
  • 3
  • 8
0

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?

Community
  • 1
  • 1
Adrian Theodorescu
  • 11,664
  • 2
  • 23
  • 30