Marian
Marian

Reputation: 7482

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

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);

Upvotes: 23

Views: 5142

Answers (2)

Sourav Ghosh
Sourav Ghosh

Reputation: 134396

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; [...]

Upvotes: 36

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385385

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.

Upvotes: 7

Related Questions