[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");
}
argv crashing application
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?
It certainly is.
You will want to check to see that argc is > 1 before checking the contents of argv[1].
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:
For reference: strcmp.
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 HutchReally, 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.
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:
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)
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."
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement