Is it legal to pass a null-terminated string to strncmp in C?

I have an array of 16 bytes that contains the name of the executable segment.

char segname[16]; 

If the length of the segment name is less than 16 bytes, then the rest is filled with zero bytes. Otherwise, the null byte does not end.

I want to compare segname with various strings, for example. __text .

Can strncmp be called with a null-terminated string?

This post assumes that it is legal. This source code makes it legal. But my man page says:

The strncmp() function lexicographically compares strings with zero termination s1 and s2 .

The size passed to strncmp will be the size of segname .

I wonder what I should talk about.

+45
c standards standard-library strncmp
Jan 01 '16 at 20:31 on
source share
2 answers

According to C99, section 7.21.4.4, ยง3, this is legal:

The strncmp function returns an integer greater than, equal to, or less than zero, respectively, since the array with the zero termination pointed to by s1 is greater than or less than the array with the zero termination pointed to by s2 .

Note, however, that it says an array of characters. By definition, if an array of characters does not have a zero end, this is not a string.

+66
Jan 01 '16 at 20:37
source share

The strncmp function compares no more than n characters (characters that follow the 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 do not match null characters are not compared, so it expects a null character or character string. one

Here you can also use characters with a non-zero trailing character, but in this case we must specify the length to which we must check it, which is useful in some cases.

<i> Corrections




[1] The fact that characters that do not match a null character are not compared does not mean that strncmp expects a null-terminated string. It just means that strncmp needs a special case to say (for example) that abc\0def ... and abc\0xyz ... compare the same. There is nothing wrong with comparing two char arrays that don't end with zero (up to the specified length) or compare one array with char zero termination with another that is not sub zero terminated >
This is added directly from David Hammen 's comment .

+14
Jan 01 '16 at 20:35
source share



All Articles