argv crashing application

Started by
5 comments, last by Zahlman 16 years ago
Im checking argv using an if command in C. If start the application up using the command prompt and put in the -i it works fine and I can put in the IP address. If I just launch it with out any extra commands it crashes. Ive narrowed it down to the if(argv check below. Is it because im trying to check an array that has nothing in it?
[source lang=c]
  if(argv[1][0] == '-' && argv[1][1] == 'i')
    {
      printf("Server Address Please?\n");
      grabString(SERVERADDRESS);
    }
  else
    {
      printf("server address go\n");
      strcpy(SERVERADDRESS,"192.168.1.102");
    } 

Do or do not there is no try -yoda
Advertisement
It certainly is.

You will want to check to see that argc is > 1 before checking the contents of argv[1].
Tromack's correct. Since argv[0] is always set, and the last element of argv is NULL, source code that would properly check everything is:

if (argv[1] != NULL && strcmp(argv[1], "-i") == 0){    printf("Server Address Please?\n");    grabString(SERVERADDRESS);}else{    printf("server address go\n");    strcpy(SERVERADDRESS,"192.168.1.102");} 


For reference: strcmp.
Quote:Original post by Hutch
Tromack's correct. Since argv[0] is always set, and the last element of argv is NULL, source code that would properly check everything is:
Really, I've never heard that argv is a null-terminated list of null-terminated strings? That would make me wonder why there is even an argc.
The code you posted might work okay in this case, but it would fall over if you were to hard code a second case that say checked argv[2] for NULL etc.
This is why is it best to check argc instead.
if (argvc > 1 && strcmp(argv[1], "-i") == 0)
Then the following is also okay:
if (argvc > 2 && strcmp(argv[2], "-j") == 0)
whereas this is not:
if (argv[2] != NULL && strcmp(argv[2], "-i") == 0)
"In order to understand recursion, you must first understand recursion."
My website dedicated to sorting algorithms
Quote:Original post by iMalc
Really, I've never heard that argv is a null-terminated list of null-terminated strings?


Section 3.6.1 paragraph 2 of the C++ Standard: "The value of argv[argc] shall be 0."
Okay thanks, I figured as much.
"In order to understand recursion, you must first understand recursion."
My website dedicated to sorting algorithms
It's intended to let you do things like 'while (*argv) { parse(*(argv++)); }'.

This topic is closed to new replies.

Advertisement