Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strcmp behaviour

Tags:

c

string

strcmp

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)
like image 634
Ashish Vyas Avatar asked Feb 08 '11 12:02

Ashish Vyas


People also ask

What is the example of strcmp?

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.

What is strcmp?

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.

What does strcmp return in C?

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 .

Which library is strcmp?

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.


2 Answers

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.

like image 68
Maxim Egorushkin Avatar answered Oct 14 '22 04:10

Maxim Egorushkin


You need to:

  • Include the proper headers, or declare functions manually. For strcmp(), you need <string.h>.
  • Not pass an invalid pointer such as NULL to strcmp(), since it doesn't protect against it and will dereference the pointer, thus causing undefined behavior in your program.
like image 32
unwind Avatar answered Oct 14 '22 04:10

unwind