1
int main()
{
    int a[2] = {1,2};
    a[2] = 3;
    printf("\n\n%d  %d  %d\n\n",a[0],a[1],a[2]);
    return 0;
}

I get output as 1 2 3

Why no error is thrown at run time or compile time?

Vaibhav Jain
  • 3,683
  • 3
  • 24
  • 41

3 Answers3

13

Have you heard about all the security problems caused by buffer overruns? They exist because C doesn't have any automatic array bounds checking. It's the programmer's responsibility to ensure that they don't address outside the array limit, the compiler doesn't check for it.

Barmar
  • 669,327
  • 51
  • 454
  • 560
  • C doesn't *require* automatic array bounds checking. Attempting to access an array outside its bounds has *undefined behavior*. A C compiler could legally implement bounds checking, but most don't – Keith Thompson Aug 16 '13 at 05:12
  • And obviously his doesn't, which explains what he sees. – Barmar Aug 16 '13 at 05:15
  • @Barmar, I think it's also important to note that its technically undefined behaviour as another variable/constant (from a future stack frame or previous stack frame) could be constantly writing and reading to/from a subset of that block of memory -- meaning he should not always expect that result. – Jacob Pollack Aug 16 '13 at 05:17
0

Just make sure you don't address anything out of the boundary since, C doesn't check array bounds.

user2687481
  • 1,195
  • 3
  • 10
  • 8
0

int a[2] is allocated as an automatic variable on the stack. In Windows the stack is initially allocated as 1MB for a process. So, what has really happened is that when the code assigned a[2] = 3; an area outside of the stack frame for main() was updated.

More often than not this causes a problem, such as a segmentation fault, but in simple programs stuff like this sometimes still works.

An interesting test would be to call a sub-routine that also defines and sets some automatic variables and after it returns print the value of a[2] to see if it got overwritten by the stack frame for the sub-routine? If you do this, please let me know the results!

JackCColeman
  • 3,707
  • 1
  • 13
  • 20