Is it legal to pass a non-null-terminated string to strncmp in C?
Solution 1:
According to the C99 standard, section 7.21.4.4, §3., it is legal:
The
strncmp
function returns an integer greater than, equal to, or less than zero, accordingly as the possibly null-terminated array pointed to bys1
is greater than, equal to, or less than the possibly null-terminated array pointed to bys2
.
Notice, however, that it says array of characters. By definition, if an array of characters is not null-terminated, it is not a string.
Solution 2:
The strncmp function compares not more than n characters (characters that follow a null character are not compared) from the array pointed to by s1 to the array pointed to by s2.
Specification 7.24.4.2 says that.C11 standard.
Characters that don't follow a null charcaters are not compared so it expects null ended character array or string.1
You can use non-null terminated characters too in here but in that case we have to specify the length upto which we have to check it which is useful in some cases.
Corrections
[1] That characters that don't follow a null character are not compared does not mean that strncmp
expects null-terminated strings. It just means that strncmp
needs a special case so as to say (for example) that abc\0def
... and abc\0xyz
... compare equal. There's nothing wrong with comparing two char arrays that aren't null-terminated (up to the specified length) or comparing one null terminated char array with another that isn't null terminated
This is directly added from the comment of David Hammen