Search code examples
cstringstrncmp

"a " equal to "exit"?


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.


Solution

  • 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 ) ...