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?
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?
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.
Just make sure you don't address anything out of the boundary since, C doesn't check array bounds.
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!