The following code snippet:
void (*foo)();
char X[1];
char Y[10];
could intruitively give me one possible stack layout of:
| Y[10] |
|---------|
| X[1] |
|---------|
| foo |
|---------|
I examined this by generating the ASM file using:
gcc -S -o stack stack.c
Then I oberved that the order of pushing these variables is different. So, if I accidentally did a X[1] I was expecting to address Y[0] but in the actual layout, writing something into X[1] overwrites the first byte of the memory location allocated to foo. Is the reorganization a compiler optimization step or can someone tell me why this is happening?
Why do you say “should”?
Of course, your suggested stack layout would be the result of one particular–very obvious–way of implementing automatic variables, but there is nothing that requires it.
Thus, no “should”.
To force the order of some items in memory so that you can play (behavior unspecified, totally unsafe and unportable!) games with overwriting, use a
structand your compiler’s padding#pragmas.