Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected address output

Tags:

c

pointers

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.

like image 944
Zoneur Avatar asked Mar 07 '14 07:03

Zoneur


3 Answers

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.

like image 126
Lee Duhem Avatar answered Nov 13 '22 00:11

Lee Duhem


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.

like image 24
elixenide Avatar answered Nov 13 '22 01:11

elixenide


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.

like image 5
Lundin Avatar answered Nov 13 '22 01:11

Lundin