Performing some tests on how c compilers (in my case g on linux) behave when allocating local variables on the stack. Take a look at this simple code:
#include <iostream>
int main()
{
int prev = 10;
int myArr[5] = {4, 5, 7, 2, 1};
int next = 10;
return 0;
}
All of these variables are allocated on the stack. One would think that that segment of the stack looks like this:
prev myArr next
But when inspecting the stack with gdb, it looks like this:
0x7fffffffd640: 0xf7dd1fc8 0x00007fff 0x0000000a 0x0000000a
0x7fffffffd650: 0x00000004 0x00000005 0x00000007 0x00000002
0x7fffffffd660: 0x00000001 0x00007fff 0x2cf9f100 0x09108235
As you can see from the 0x0000000a values, both int variables are allocated before the array. Why is this the case? Some kind of optimization putting the larger int-array after the smaller 4byte ints or am i missing something?
Thanks in advance Best regards
CodePudding user response:
One would think that that segment of the stack looks like this:
prev myArr next
This order is not guaranteed.
Some kind of optimization putting the larger int-array after the smaller 4byte ints or am i missing something?
Yes, the compiler may arrange the objects as it likes. Order of objects on the stack is not specified and may differ.
A variable may not even be allocated on the stack at all when the compiler sees that it isnt necessary. For example this:
int main() {
int x = 42;
return x;
}
is equivalent to
int main() {
return 42;
}
When optimizations are turned on the compiler should notice that and make use of the as-if-rule to produce optimized output.
