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.
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.
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.
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.
yes it is perfectly safe and considered standard practice. String literals are guaranteed to be properly null terminated.
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