Possible Duplicate:
Order of local variable allocation on the stack
(C program on x86_64 Linux) I am trying to understand the way variables are assigned to stack memory. As I understand it, variables in a stack frame move toward lower memory addresses. The program below shows this.
int main() {
int i = 6;
char buffer[8];
return 0;
}
Program was compiled as: gcc -g prog.c
Debugging shows:
(gdb) x/x &i
0x7fffffffe04c: 0x00000006
(gdb) x/x buffer
0x7fffffffe040: (random data)
The character array has a lower memory address than the integer i variable. My question is how come when the order of declarations are reversed as seen below, the integer variable i is still at a memory address greater than the character array?
int main() {
char buffer[8];
int i = 6;
return 0;
}
(gdb) x/x &i
0x7fffffffe04c: 0x00000006
(gdb) x/x buffer
0x7fffffffe040: (random data)
This issue does not seem to occur for the ordering of say strictly single integer variables. If the order of integer declarations were switched, the earliest declared would have a higher memory address in the stack frame. The concern here is why this occurs for the character array. I have read this answer here in another post but I am wondering if anyone has a definitive explanation on this one.