I’m a newbie to C, and I have been testing my program out in Fedora, using gcc and gdb to debug. I have a program that takes input from the user. If the first string entered is “create” then I take a look at the second command, and if that’s “object” then I proceed to the createObject function.
Hopefully my code will make this a bit clearer:
static void parseCmd(char **input) {
if(!strcmp(input[0], "create")) {
if(!strcmp(input[1], "object")) {
if(input[2] && strcmp(input[2], ""))
createObject(input[2]);
else
printf("Object needs a name\n");
}
else
printf("Command needs more parameters\n");
}
else
printf("Command not recognized\n");
}
When I test entering just “create object” (no space after object, just the ENTER key)
In Linux it prints “Object needs a name”
But in windows the program crashes, it just hangs. How could I change the code to make it behave the same way as it does in Linux?
You’ve entered into the realm of potential access violations or undefined behavior (well, undefined values):
If the length of
inputis only 2, then this is reading past the acceptable point to read. Worst case this will cause a segfault (as Windows does), and best case the OS will let it happen and you’ll get a random value in it. (Linux appears to be treating either it or *input[2] as 0 though.)Anyway, rather than reading contents you are not allowed to access, pass in the length of the input and check that instead.
–Edit–
As pointed out by Daniel Fischer, apparently
argv[argc]is indeed a valid read, and it is guaranteed to be a null pointer.Assuming that you are indeed passing
argvto the function, this means that you could rely on this behavior. Your other two if statements do not check for this though, and for the sake of generalizing the function, it’s still better to pass along the length (or, as paulsm4 said, you should look into the getopt function — it makes parses parameters much easier than rolling your own parsing method).