0

Why does this code work? I have an array of 2 elements and it should overflow, but it does not even give me an error on Linux using gcc. Instead, it works and outputs 5.

int doS(int a[2])
{

printf("%d", a[4]);

}

int main()

{


int rows =2;

int a[rows];

a[0] = 1;
a[1] = 2;
a[2]= 3;
a[3] = 4;
a[4] = 5;

doS(a);
}
  • 2
    This means you are under the dark magic of undefined behavior! Reading about it will break the spell. – haccks Aug 14 '18 at 08:24
  • *"Why does this code work?"* - It doesn't. You were lulled into the false sense that it does simply because it appears to do so. You're confusing *defined* behavior with *observed* behavior. The latter doesn't necessarily equate to the former, but the former will reliably lead to the later. – WhozCraig Aug 14 '18 at 08:33
  • Because what happens when you trigger Undefined Behavior is undefined. Your harddrive getting formatted is a valid result too. – Petr Skocik Aug 14 '18 at 08:44

1 Answers1

0

There is no guarantee that it always works! a[2], a[3] and a[4] are out of memory. Behaviour of the code is called as Undefined Behaviour

For example, try below one. Does it still work?

for (int i = 0; i < 100; ++i) {
        a[i] = i + 1;
}