The following snippet is intentionally accessing the next sizeof(int) bytes following t[4]
, so I am aware of the mistake that is being made here. I am just doing this as an experiment to see how the compiler handles the stack allocations.
int t[5], i;
for (i = 0; i <= 5; i++) {
t[i] = 0;
}
When executing this code on Windows, using a ported version of the GNU C Compiler, the program always gets stuck in an infinite loop. I am sure that this could only happen because t
and i
are allocated sequentially on the stack one after the other and t[5]
points to to the same address as the i
variable. Therefore, when executing t[5] = 0
the program actually sets the value of i
to zero.
However, when compiling this with a different version of the GNU C Compiler, I never get the infinite loop. The address of t[5]
is not the same as the address of i
.
My question is, why this different behavior? I know you should not assume anything about the outcome of this, but is it not the case that stack allocations should happen in the same way?
What I am really curious about is how does the compiler manage those stack allocations. Is there any padding? Is the order always the same as in the source code? Obviously this has nothing to do with the C standard and there are differences between implementations, or even different versions of the same compiler. I am curious though what are the possible outcomes and considerations in this particular case.