cmemorymemory-address

How C variable usage changes its memory address?


This code shows that b variable is placed right after a variable:

#include <stdio.h>
int main(void)
{
    int a;
    int b;
    a=15;
    b=2654;
    printf("%d %d\n", a, b);
    &a;
    printf("%d %d\n", a, *(&b-1));
}

Outputs

15 2654
15 15

But when I delete &a; b is no longer right after a:

int main(void)
{
    int a;
    int b;
    a=15;
    b=2654;
    printf("%d %d\n", a, b);
    printf("%d %d\n", a, *(&b-1));
}

Outputs

15 2654
15 21927

Why when I don't get address of a variable then a and b aren't placed near each other? Is it related to compiler optimization?


Solution

  • Probably register allocation. Since the address of a is never taken, its perfectly reasonable for the compiler to put it in a register.

    It's also perfectly reasonable on such a short function for the compiler to simply delete a altogether and pass a constant to printf.

    In general you can't do this; on larger functions the compiler tends to use hash objects in memory allocation; resulting in no discernible relation between variable declaration order and variable order on the stack.