1

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.

Xirol
  • 303
  • 4
  • 10
  • argv[0] = '/a.out', and argv[1] would be "hello". When you run it without the 'hello', you'll get the error. – bpm Feb 03 '16 at 04:11

1 Answers1

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.

Community
  • 1
  • 1
christutty
  • 952
  • 5
  • 12
  • So in this case, I should be using an if statement or something of the sort to fix that right? – Xirol Feb 03 '16 at 04:20
  • Yes thats right, as **christutty** suggested in the code he gave. – Ahmed Akhtar Feb 03 '16 at 04:39
  • @AhmedAkhtar - I edited my answer in response to the first comment so the code you're referring to didn't exist when that comment was posted. That's a source of frequent confusion at SO so remember that comments don't always relate to the current version of the answer. – christutty Feb 03 '16 at 04:44