问题
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.
回答1:
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).
回答2:
The address returned for a local variable in the user space is always a virtual address not the physical address.
The variable a
in your case is allocated on the local storage(stack) and every time you execute your program a stack space allocated to your function, the variable is located at particular offset within this stack frame, since the address of the stack being allocated to your program can be different everytime the address returned for the variable will be different as well.
回答3:
On any modern OS all addresses that you ever see on a C level are virtual addresses. The example that you give is a variable on the stack, and the reason why this'd be different on every execution is that the (virtual) stack address is randomized for security reasons.
But in any case, even global symbols that are resolved by the loader have virtual addresses in the address space of the process.
(All of this might not be true for embedded devices but this is usually nothing that you will encounter when learning C)
回答4:
I mean is this a compiler generated address i.e. virtual address or the loader given physical address in the RAM.
False dichotomy. The address generated by the compiler is relocated by the linker, and it is this address that is returned by &. It is a virtual address unless you are running on something odd like NetWare 3 that doesn't use VM.
来源:https://stackoverflow.com/questions/9613786/address-of-gives-compiler-generated-address-or-loader-generated-address