Sorry if this is a noob question :( .
Piece of C code.
int array[5];
int cnt;
for(cnt = 0; cnt <= 10; cnt+=1)
{
array[cnt] = cnt;
}
Should give an error, right? No! Works fine! But why is that? It seems that -in the first line- an array of more than the double size (11) is defined. You can even access array[5 to 10] later on. And that is confusing me. It stops working when you define array[4 or less] ...
Thanks in advance.
I just like to point out that all this is indeed undefined. Your example "works" in this specific example because both variables are located on the stack. That is the address of cnt is just below the end of the array. When cnt reaches cnt==5 the statement array[cnt]=cnt; does not write in the memory dedicated to the array but just after it, where the address of cnt lay. It is just luck that it does not alter your counter. When cnt>5 there is no memory to trash and it will just write in the "stack void" (don't know the proper word).
another example to illustrate this:
output:
The last two writes of the loop overwrites the stack data after a[] and may yield very confusing errors. In this case the cnt2 is trashed.
Depends on how the stack memory is packed. Also, it will happily overwrite those values and even read them, but most likely you are corrupting the stack.
This only "works" if your definition of "works" is synonymous with "hasn't crashed yet".