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);
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.
In few words: strncmp is safer then strcmp, but it is slower too. M.L. M.L. strncmp and strcmp have different semantics.
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).
C++ strncmp() The strncmp() function in C++ compares a specified number of characters of two null terminating strings. The comparison is done lexicographically.
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; [...]
From the C strncmp
documentation at cppreference.com:
The behavior is undefined when either
lhs
orrhs
is the null pointer.
Simply read the documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With