Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advantages of strncmp over strcmp?

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"));
like image 966
Thomson Avatar asked May 12 '15 12:05

Thomson


People also ask

When would you use a strncmp?

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.

What problem of strcmp is solved by strncmp?

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.

What is difference between strcmp () and Strcasecmp ()?

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.


1 Answers

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.

like image 98
Surajeet Bharati Avatar answered Sep 16 '22 23:09

Surajeet Bharati