I am trying to figure out how the addresses are assigned to variables located on the stack. I ran the little program below:
int main()
{
long a;
int b;
int c;
printf("&a = %p\n", &a);
printf("&b = %p\n", &b);
printf("&c = %p\n", &c);
}
The output I expected was (considering addresses are going down):
&a = 0x7fff6e1acb88
&b = 0x7fff6e1acb80
&c = 0x7fff6e1acb7c
But instead I got:
&a = 0x7fff6e1acb88
&b = 0x7fff6e1acb80
&c = 0x7fff6e1acb84
How come the c
variable is located between the a
and b
variable? Are variables not put on the stack as they are declared?
I tried replacing the type of a
from long
to int
and I got this:
&a = 0x7fff48466a74
&b = 0x7fff48466a78
&c = 0x7fff48466a7c
Here I don't understand why are the addresses going up, while they were going down previously?
I compiled the program using gcc version 4.7.2 (Ubuntu/Linaro 4.7.2-11precise2)
, if that's of any help.
Are variables not put on the stack as they are declared?
No.
why are the addresses going up, while they were going down previously?
They could going up, but they do not have to.
Compilers is free to rearrage the order of local variables that it sees is fit, or it could even delete or add some.
Variables are not necessarily put on the stack in the order in which they are declared. You can't predict where on the stack they will be -- they could be in any order. As glglgl pointed out in the comments, they don't even have to be on the stack and could simply be held in registers.
Even though the stack pointer is counting downwards on your given CPU, the program will be using stack frames. How a certain parameter is allocated inside the stack frame is implementation-defined.
Also note that some CPUs have up-counting stack pointers.
Also note that local variables are not necessarily allocated on the stack. More often, they are allocated in CPU registers. But when you take the address of a variable, you kind of force the compiler to allocate it on the stack, since registers have no addresses.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With