14

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)
Alexander Malakhov
  • 3,383
  • 2
  • 33
  • 58
Ashish Vyas
  • 617
  • 1
  • 5
  • 19

3 Answers3

30

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.

Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
  • Well, I did not do any compiler settings to turn on optimization, however it does it automatically. You were spot on. – Ashish Vyas Feb 08 '11 at 12:30
  • 2
    gcc does SSA which works even with no optimizations enabled. SSA can remove dead code. http://en.wikipedia.org/wiki/Static_single_assignment_form – Maxim Egorushkin Feb 08 '11 at 12:48
6

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.
unwind
  • 391,730
  • 64
  • 469
  • 606
3

What you are doing is undefined. strcmp requires valid pointers to null-terminated strings.

NULL is not a pointer to a null-terminated string.

Benoit
  • 76,634
  • 23
  • 210
  • 236