When I run the following code:
#include
int main(int argc, char *argv[])
{
int p = 0;
p = strcmp(NULL,\"foo\");
return 0;
}
What you are doing is undefined. strcmp
requires valid pointers to null-terminated strings.
NULL
is not a pointer to a null-terminated string.
You are probably using optimization options when compiling. Since the result of strcmp()
in the second snippet is ignored the compiler eliminates this function call and this is why your program does not crash. This call can be eliminated only because strcmp()
is an intrinsic function, the compiler is aware that this function does not have any side effects.
You need to:
strcmp()
, you need <string.h>
.strcmp()
, since it doesn't protect against it and will dereference the pointer, thus causing undefined behavior in your program.