Search code examples
ccompiler-constructionvirtualloadermemory-address

Address of (&) gives compiler generated address or loader generated address?


int a;
printf("address is %u", &a);

Which address is this..? I mean is this a compiler generated address i.e. virtual address or the loader given physical address in the RAM..?

As it prints different address every time, I guess it must be address in the RAM. Just want to make sure.

Please provide any links which give reference to your answer.


Solution

  • The correct answer is: "it depends."

    (The printf should use the "%p" directive, and cast the address to "void *", for the sake of well-defined-ness:

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

    although using %u no doubt works for your particular compiler with whatever flags you are using.)

    As @Alex noted, the address is virtual if translation is going on (as with most modern OSes, or even when running in "emulated physical" under a virtual machine). The address itself is generally determined at link or load time if "a" has static storage duration, but at runtime (on the stack as @Als said) if not. Variables declared "static" or "extern" have static duration; variables declared outside function bodies have static duration; and variables declared within function bodies, but without using either "extern" or "static", have automatic storage duration (and are thus usually on "the stack"—though there can be more than one stack, as when using POSIX threads).