Issue
I have the following code
int main(int argc, char *argv[]) {
int value1 = 10;
int value2 = 11;
return 0;
}
When I debugged the code, &value2 was higher than &value1. That means that value2 was pushed to the stack first, then value1.
Is this a normal behavior of gcc?
Why does the gcc compile variables from bottom up?
Does clang also behave in the same way?
Thanks
Solution
The ordering of local variables on the stack is entirely implementation dependent and need not appear consistent.
When compiled the above code with gcc 4.8.5 and ran it, value1
had a higher address than value2
which is in contrast to what you saw.
I also tried running this in gdb:
int main(int argc, char *argv[]) {
int value1 = 10;
int x = 4;
int value2 = 11;
printf("&1=%p, &2=%p\n", &value1, &value2);
return 0;
}
And got this:
(gdb) start
Temporary breakpoint 1 at 0x40053c: file x1.c, line 6.
Starting program: /home/dbush/./x1
Temporary breakpoint 1, main (argc=1, argv=0x7fffffffe008) at x1.c:6
6 int value1 = 10;
Missing separate debuginfos, use: debuginfo-install glibc-2.17-196.el7.x86_64
(gdb) step
7 int x = 4;
(gdb)
8 int value2 = 11;
(gdb)
10 printf("&1=%p, &2=%p\n", &value1, &value2);
(gdb) p &value1
$1 = (int *) 0x7fffffffdf18
(gdb) p &value2
$2 = (int *) 0x7fffffffdf14
(gdb) p &x
$3 = (int *) 0x7fffffffdf1c
(gdb)
In this case, the address of x
comes after value1
and value2
even though it is defined between them.
What this shows is that you can't make any assumptions about the order of variables on the stack.
Answered By - dbush