3

Possible Duplicate:
Why don’t I get a segmentation fault when I write beyond the end of an array?

This code compiles and runs without any error. But how?

#include <stdio.h>

int main (void)
{
    int foo[2];

    foo[8] = 4; /* How could this happen? */

    printf("%d\n", foo[8]);

    return 0;
}

I'm compiling with GCC 4.7.2 on Arch Linux x86_64.

gcc -Wall -o "main" "main.c"
Community
  • 1
  • 1

3 Answers3

5

Because undefined behavior doesn't mean "you will receive a segfault", that would be defined behavior.

Let's assume you're running in debug mode and your compiler is padding your stack/local variable space. You're probably just writing into some unused part of the stack space.

Build a release version on a Monday when your compiler is feeling cranky and now you overwrite the return address, or the code that sets up the call to printf, whatever. Oops.

Just one possible outcome, but you get the idea.

Ed S.
  • 122,712
  • 22
  • 185
  • 265
1

foo[8] may be allocated for your program (padding purpose, for instance), belong to your operating system. With an undefined behavior, anything can happen; you are unlucky, because it works.

md5
  • 23,373
  • 3
  • 44
  • 93
0

Try

foo[1000000]=42; 

and see what happens.

alk
  • 69,737
  • 10
  • 105
  • 255