I am running the following program and got errors:
First-chance exception at 0x0f32d440 (msvcr100d.dll) in c.exe: 0xC0000005: Access violation reading location 0x00000000.
Unhandled exception at 0x772815de in c.exe: 0xC0000005: Access violation reading location 0x00000000.
The program '[9048] c.exe: Native' has exited with code -1073741510 (0xc000013a).
Here is the code
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[], char *env[]) //char *argv[]
{
int i;
printf("These are the %d command- line arguments passed to main:\n\n", argc);
if(strcmp(argv[1],"123")==0)
{
printf("success\n");
}
else
for(i=0; i<=argc; i++)
//if(strcmp(argv[1],"abc")==0)
printf("argv[%d]:%s\n", i, argv[i]);
/*printf("\nThe environment string(s)on this system are:\n\n");
for(i=0; env[i]!=NULL; i++)
printf(" env[%d]:%s\n", i, env[i]);*/
system("pause");
}
The problem should be with the strcmp function but I dont know how to solve it. Could anyone help?
You have (at least) two problems.
The first is doing this:
if(strcmp(argv[1],"123")==0)
without first checking that argc >= 2
.
The second is this:
for(i=0; i<=argc; i++)
in that you should be processing arguments 0
thru argc - 1
inclusive. What that loop does is process arguments 0
through argc
and argv[argc]
is always NULL
.
The following program illustrates one way to fix this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (int argc, char *argv[]) {
int i;
printf ("These are the %d command-line argument(s) passed to main:\n", argc);
if ((argc >= 2) && (strcmp (argv[1], "123") == 0)) {
printf (" success\n");
} else {
for (i = 0; i < argc; i++) {
printf (" argv[%d] = [%s]\n", i, argv[i]);
}
}
return 0;
}
You can see that the comparison with "123"
is only done after ensuring that argv[1]
is populated correctly. In addition, the loop has been changed to exclude argv[argc]
since that's not one of the arguments. A transcript follows:
pax> testprog
These are the 1 command-line argument(s) passed to main:
argv[0] = [testprog]
pax> testprog 123
These are the 2 command-line argument(s) passed to main:
success
pax> testprog a b c
These are the 4 command-line argument(s) passed to main:
argv[0] = [testprog]
argv[1] = [a]
argv[2] = [b]
argv[3] = [c]
for(i=0; i<=argc; i++)
should be for(i=0; i<argc; i++)
.
C/C++ arrays are 0 to n-1. You are running 1 spot off the end of the array.
User contributions licensed under CC BY-SA 3.0