By my understanding, strcmp()
(no 'n'), upon seeing a null character in either argument, immediately stops processing and returns a result.
Therefore, if one of the arguments is known with 100% certainty to be null-terminated (e.g. it is a string literal), there is no security benefit whatsoever in using strncmp()
(with 'n') with a call to strlen()
as part of the third argument to limit the comparison to the known string length, because strcmp()
will already never read more characters than are in that known-terminating string.
In fact, it seems to me that a call to strncmp()
whose length argument is a strlen()
on one of the first two arguments is only different from the strcmp()
case in that it wastes time linear in the size of the known-terminating string by evaluating the strlen()
expression.
Consider:
Sample code A:
if (strcmp(user_input, "status") == 0)
reply_with_status();
Sample code B:
if (strncmp(user_input, "status", strlen("status")+1) == 0)
reply_with_status();
Is there any benefit to the former over the latter? Because I see it in other people's code a lot.
Do I have a flawed understanding of how these functions work?