Consider this code:
#include <stdio.h>
int gprs[32];
int main(void)
{
printf("%p\n", (void*)&gprs);
}
being compiled with -pie (seems to be the default) produces:
0x55c183951040
while being compiled with -no-pie produces:
0x404060
Can someone explain how -pie affects address of file scope variable?
Note: Clang seems to have -no-pie by default.
Using
-pie, the operating system can load the executable file to any address in memory. Under Windows, this is done using a "base relocation table"; under Linux this is done using "position-independent code".In this case, many modern OSs load an executable file to any (random) address in memory for security reasons (because it is harder to write a virus accessing the variable
gprsif its address is not known).This means that the difference between the addresses of the (
staticor global) variablesaandbin the following example:... should be constant but the address of
a(andb) may be different every time you run the program.Using
-no-pie, "position-dependent code" is generated under both OSs and no "base relocation table" is generated under Windows.This means that the executable file can only be loaded into a fixed memory address. And for this reason, the address of a
staticor global variable (but not necessarily of a non-staticlocal variable) should not change when you run the program multiple times.