Advantages of strncmp over strcmp?

Thomson picture Thomson · May 12, 2015 · Viewed 27.4k times · Source

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"));

Answer

Surajeet Bharati picture Surajeet Bharati · May 12, 2015

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.