Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Local variables adresses in C

I have this little Program:

#import <stdio.h>
#import <stdlib.h>

void main(void) {

    char a;
    char b;

    printf("Adress a: %p\n", (void *)&a);
    printf("Adress b: %p\n", (void *)&b);

    return 0;
}

The adress of b is lower, than the adress of b. Why is it like this? Or am i doing something wrong?

like image 829
andred Avatar asked Apr 25 '13 07:04

andred


2 Answers

The storage space for a local variable is on the stack. The X86 processor family has a stack which "grows downward". This means that as allocations occur (for example assigning a variable), the stack pointer is moved downwards toward lower memory addresses.

&a is greater than &b because after &a was assigned, the stack pointer was moved downward to a lower address for the next allocation.

like image 71
Crippledsmurf Avatar answered Oct 04 '22 15:10

Crippledsmurf


In your case the stack grows down.

a and b are allocated on the stack in order of definition. So you have that &a is higher than &b.

like image 30
Alex Avatar answered Oct 04 '22 17:10

Alex