Seems strncmp
is usually recommended than strcmp
, what are the advantages? I think it could be related to security. If this is the case, is it still applicable if one of the input string is known to be literal constant, like "LiteralString"
?
UPDATE:
I mean under the same user scenario where whole strings need to be compared, and strncmp
can be used as below. I am wondering it makes sense or not.
strncmp(inputString, "LiternalString", strlen("LiternalString"));
Presuming that the string in message is supposed to be null-terminated, the only reason to use strncmp() here rather than strcmp() would be to be to prevent it looking beyond the end of message , in the case where message is not null-terminated.
The function strncmp() is used to compare left string to right string up to a number. It works same as strcmp(). It returns a value greater than zero when the matching character of left string has greater ASCII value than the character of the right string.
The "strcasecmp()" function is a case insensitive string comparison function. This function compares two strings; the strcmp() function is case sensitive but the strcmp() and strcasecmp() functions both work the same. But it does not distinguish between uppercase and lowercase letters.
The problem with strcmp
is that sometimes, if by mistake, arguments that are passed are not valid C-strings (meaning that p1 or p2 is not terminated with a null character i.e. not NULL-terminated String), then, strcmp continues comparing until it reaches non-accessible memory and crashes or sometimes results to an unexpected behaviour.
Using strncmp
you can limit the search, so that it doesn't reach non-accessible memory.
But, from that, it should not be concluded that strcmp
is insecure to use. Both the functions work well in the way they are intended to work. Programmer should read man
page for that function before using it and must be sincere enough while passing parameters to such library functions.
You can also read THIS which contains an almost similar question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With