Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading