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

6.3k views Asked by At

I have an array of 16 bytes that holds the name of an executable's segment.

char segname[16];

If the segment name length is less than 16 bytes, then the rest is padded with null bytes. Otherwise, there is no terminating null byte.

I want to compare segname to various strings, e.g. __text.

Is it legal to call strncmp with a non-null-terminated string?

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

The strncmp() function lexicographically compares the null-terminated strings s1 and s2.

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

I'm wondering what I should refer to.

2

There are 2 answers

12
giusti On BEST ANSWER

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 by s1 is greater than, equal to, or less than the possibly null-terminated array pointed to by s2.

Notice, however, that it says array of characters. By definition, if an array of characters is not null-terminated, it is not a string.

10
user2736738 On

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