Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Am I correct that strcmp is equivalent (and safe) for literals?

Tags:

c

strcmp

We all know the trouble overflows can cause, and this is why strn* exist - and most of the time they make sense. However, I have seen code which uses strncmp to compare commandline parameters like so:

if(... strncmp(argv[i], "--help", 6) == 0

Now, I would have thought that this is unnecessary and perhaps even dangerous (for longer parameters it would be easy to miscount the characters in the literal).

strncmp stops on nulls, and the code already assumes argv[i] is null-terminated. Any string literal is guaranteed to be null-terminated, so why not use strcmp?

Perhaps I'm missing something, but I've seen this a few times and this time it intrigued me enough to ask.

like image 698
Draemon Avatar asked Jan 15 '09 21:01

Draemon


People also ask

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.

Can you compare string literals in C?

You can't compare strings with == in C. For C, strings are just (zero-terminated) arrays, so you need to use string functions to compare them. See the man page for strcmp() and strncmp(). If you want to compare a character you need to compare to a character, not a string.

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.


1 Answers

yes it is perfectly safe and considered standard practice. String literals are guaranteed to be properly null terminated.

like image 158
Evan Teran Avatar answered Sep 17 '22 12:09

Evan Teran