Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 737
Bilow Avatar asked Jan 01 '17 20:01

Bilow


People also ask

What happens if a string is not null-terminated in C?

Many library functions accept a string or wide string argument with the constraint that the string they receive is properly null-terminated. Passing a character sequence or wide character sequence that is not null-terminated to such a function can result in accessing memory that is outside the bounds of the object.

Does strncmp include null terminator?

The strncmp() built-in function compares at most the first count characters of the string pointed to by string1 to the string pointed to by string2. The string arguments to the function should contain a NULL character ( \0 ) marking the end of the string.

Do C strings need to be null-terminated?

Yes, you need to do that. Not all functions put the null char for you, and strncpy , as I can read in its man page, requires to have a null byte among the first n characters of src.

What happens if you don't correctly terminate the string?

If you don't include a terminating \0 you will commit a fundamental breach of contract.


1 Answers

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.

like image 130
giusti Avatar answered Sep 19 '22 12:09

giusti