0

I am running the following piece of code in C (compiled using gcc):-

#include <stdio.h>

int main() {
    float box[2][2];

    box[3][3] = 1;

    printf("%f", box[3][3]);

    return 0;
}

Output:-

1.000000

Why isn't C giving me segmentation fault/Array index out of bounds? Any help is appreciated.

nikhilbalwani
  • 817
  • 7
  • 20
  • 5
    Undefined behavior is undefined. It can do whatever it wants, including give the appearance that it is working. – Christian Gibbons Apr 19 '19 at 15:47
  • Which means there's a chance that a runtime error shows up? – nikhilbalwani Apr 19 '19 at 15:49
  • Anything can happen. Some hyperbole to get the point across: undefined behavior could result in demons flying out of your nose. It could make a runtime error show up. It could make Han shoot second. Anything and everything is a potential consequence of undefined behavior. Bottom line: Do not rely on any particular behavior upon invoking undefined behavior. – Christian Gibbons Apr 19 '19 at 15:55

1 Answers1

3

Yes, C does not prevent out of bound accesses, it specifies them as having undefined behavior.

Undefined behavior can sometimes be very confusing as the program seems to have the expected behavior.

You are modifying a block of memory beyond the end of box, which could have caused a crash, but did not (or not yet...) and reading back from it returns the written value (which again is undefined behavior, but can seem to work).

The program exits, and there is a chance that no further damage has occurred, but who knows... Modifying box[3][3] could have altered the place on the stack where the return value of the function is stored, causing a crash after main returns to its caller, or anything alse... Just hopefully not Monday's fire at Notre Dame.

chqrlie
  • 131,814
  • 10
  • 121
  • 189