When I run the following code:
#include <stdio.h>
int main(int argc, char *argv[])
{
int p = 0;
p = strcmp(NULL,"foo");
return 0;
}
I get segmentation fault. echo $? says 139. But when I run
#include <stdio.h>
int main(int argc, char *argv[])
{
int p = 0;
strcmp(NULL,"foo"); // Note removed assignment
return 0;
}
I don't get any segmentation fault. Could someone please throw some light?
Here is my gcc info:
> gcc --version
gcc (GCC) 3.4.6 20060404 (Red Hat 3.4.6-8)
Example: strcmp() function in C In the above example, we are comparing two strings str1 and str2 using the function strcmp(). In this case the strcmp() function returns a value greater than 0 because the ASCII value of first unmatched character 'e' is 101 which is greater than the ASCII value of 'E' which is 69.
strcmp() in C/C++ This function is used to compare the string arguments. It compares strings lexicographically which means it compares both the strings character by character. It starts comparing the very first character of strings until the characters of both strings are equal or NULL character is found.
The return value from strcmp is 0 if the two strings are equal, less than 0 if str1 compares less than str2 , and greater than 0 if str1 compares greater than str2 .
Description. The C library function int strcmp(const char *str1, const char *str2) compares the string pointed to, by str1 to the string pointed to by str2.
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.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