• Advertisement
Sign in to follow this  

argv crashing application

This topic is 3597 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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");
    } 

Share this post


Link to post
Share on other sites
Advertisement
It certainly is.

You will want to check to see that argc is > 1 before checking the contents of argv[1].

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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)

Share this post


Link to post
Share on other sites
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."

Share this post


Link to post
Share on other sites
It's intended to let you do things like 'while (*argv) { parse(*(argv++)); }'.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement