Segmentation Fault (core dumped) printing string from argv

时间:2016-02-03 04:06:53

标签: c

I'm just trying to check the commandline arguments and see if it works in the command line. It works fine if I execute './a.out hello' but when I do './a.out' I get the error.

#include <stdio.h>

int main(int argc, char * argv[]){
   printf("Test");
   printf("\n%s",argv[0]);
   printf("\n%s",argv[1]);
return 0;
}

The reason why I'm doing this is because I'm going to take that string and compare it later on. I don't understand why something this simple is causing an error.

1 个答案:

答案 0 :(得分:8)

You're not checking the length of argv before dereferencing the second argument. If argv only has one element argv[1] is a null reference, which causes your fault.

With C everything needs to be done carefully. To answer your question, yes, an if statement is the right approach if you want to handle the command line yourself. The argc parameter to main() is provided for exactly this purpose.

#include <stdio.h>

int main(int argc, char * argv[]){
  printf("Test");
  if (argc > 0) {
      printf("\n%s", argv[0]);
      if (argc > 1) {
          printf("\n%s", argv[1]);
      }
  }
return 0; 
}

Theoretically argv[0] is always populated with the application name so the first if is redundant but with C caution is your friend.

However, don't take this path. For everything except trivial applications you should use a parameter parsing library such as http://www.gnu.org/software/libc/manual/html_node/Getopt.html, check Christian's excellent answer here https://stackoverflow.com/a/24479532/2381157 for more options.