Yes, this behavior is undefined, some compilers give warnings about this, others do not, but let's see what your code does.
Take a look at the built-in implementation of otators []
. a[b]
is actually *(a + b)
. So go back to your code.
int data[8]; data[9] = 1;
First, you select a portion of the stack and create a pointer to the first element. Then you overwrite some data that is immediately after your array, so you will corrupt some data.
Take another example:
int data[8]; int data2[8] = {}; data[9] = 1;
It is very likely that the compiler generates code that selects once and creates two pointers in the form of arrays. Thus, data[9] = 1;
can set the second value of data2
to one, but there is no guarantee about it.
source share