Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is strncmp(NULL, "foo", 0) well defined?

Tags:

Is it safe to put NULL pointer as parameter of strncmp if the third parameter is zero? I.e. an invocation like:

strncmp(NULL, "foo", 0); 
like image 252
Marian Avatar asked Jun 23 '16 14:06

Marian


People also ask

Does strncmp check for NULL?

The strcmp() built-in function compares the string pointed to by string1 to the string pointed to by string2 The string arguments to the function must contain a NULL character ( \0 ) marking the end of the string.

Is strncmp better than strcmp?

In few words: strncmp is safer then strcmp, but it is slower too. M.L. M.L. strncmp and strcmp have different semantics.

What happens if you strcmp null?

strcmp() checks for the occurrence of NULL character in string, so that it will termination the function. It is defined in the “string. h” header file. The return value is 0, if both strings are identical (equal).

What does strncmp mean in C++?

C++ strncmp() The strncmp() function in C++ compares a specified number of characters of two null terminating strings. The comparison is done lexicographically.


2 Answers

It's undefined behavior.

C standard says you should not pass invalid pointers to library function, in general.

Quoting C11, chapter §7.24.1, "String function conventions", (emphasis mine)

Where an argument declared as size_t n specifies the length of the array for a function, n can have the value zero on a call to that function. Unless explicitly stated otherwise in the description of a particular function in this subclause, pointer arguments on such a call shall still have valid values, as described in 7.1.4. On such a call, a function that locates a character finds no occurrence, a function that compares two character sequences returns zero, and a function that copies characters copies zero characters.

and I don't see any specific mention (as an exception to the aforesaid constraint) in 7.24.4.4, strncmp() function.


To add context for "invalid pointers", quoting §7.1.4/p1, Use of library functions

[...] If an argument to a function has an invalid value (such as a value outside the domain of the function, or a pointer outside the address space of the program, or a null pointer, or a pointer to non-modifiable storage when the corresponding parameter is not const-qualified) or a type (after promotion) not expected by a function with variable number of arguments, the behavior is undefined. [...]

and regarding NULL, quoting §7.19, <stddef.h>

NULL
which expands to an implementation-defined null pointer constant; [...]

like image 175
Sourav Ghosh Avatar answered Sep 19 '22 14:09

Sourav Ghosh


From the C strncmp documentation at cppreference.com:

The behavior is undefined when either lhs or rhs is the null pointer.

Simply read the documentation.

like image 26
Lightness Races in Orbit Avatar answered Sep 20 '22 14:09

Lightness Races in Orbit