Sign in to follow this  
Xloner12

argv crashing application

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
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this