"a " equal to "exit"?

454 views Asked by At

Just messing around with a program I'm currently working on and I stumble upon this. The program is of the client-server type so the client asks the user for commands and the server performs all the executions. If the "exit" command is entered the client will stop. I'm using

if (strncmp ("exit", command, strlen (command) - 1)) == 0)
{
         //Perform exit code
}

to check if "exit" has been entered. If I enter "a " the program exits as if "exit" has been entered. Not a big deal, just wondering why it's happening.

Thanks.

4

There are 4 answers

6
Sergey Kalinichenko On BEST ANSWER

Here is what happens: when you enter "a ", the code that separates the command out makes the command string equal to "a" (no space). Its length is one. Then the code calls strncmp, telling it to compare "exit" using zero initial characters. This comparison always succeeds, because no comparisons are made at all.

Note that removing -1 from the expression may not fix the problem, because the code would then exit when you enter "e " (unless of course that is the behavior that you want to achieve). To make sure that the command is indeed "exit", you can use this condition:

if ( strlen(command) == 4 && strncmp("exit", command, 4)) == 0 ) ...
1
Mauro H. Leggieri On

Just use strcmp.

strlen("a") return 1... 1 minus 1 => zero. The third parameter is zero so the strncmp reached the "max length" without testing any char on both strings.

0
Deck On

If you enter a the length of command would be 1. Are you trying to compare the length - 1, so it would be 0. strncmp won't test any character.

I think command has char[MAX_BUFFER] type. You better pass this MAX_BUFFER as third parameter.

0
Eric Postpischil On

strlen(command) returns the number of non-zero characters in command. It does not include the terminating zero character. Thus, strlen(command) - 1 is one less than the number of non-zero characters. When command contains “a”, strlen(command) - 1 is 0.

Then strncmp("exit", command, strlen(command) - 1) compares zero characters of “exit” to zero characters of command. The result of comparing zero characters is always equality, because an empty string is equal to an empty string. To fix this, do not compare zero characters. Either change the length passed to strncmp to be what you want or use strcmp to compare the entire strings.

If you want to compare the entire string “exit” to the entire string in command, use:

if (strcmp("exit", command) == 0) …

If you want to allow command to be an abbreviation for “exit”, so that the commands “e”, “ex”, “exi”, and “exit” are accepted for “exit”, then use:

if (strncmp("exit", command, strlen(command)) == 0) …