I have small code snippet like below:
char global=100;
void main()
{
char p = NULL;
printf("%p\n", &p);
printf("%p\n", &global);
}
Once after compiling and generating a binary executable image, on every execution of the same binary executable, I see different virtual memory address for the local variable p
.
However, the virtual memory address of the global variable global
remains the same.
I understand the C memory layout; and I expect the same memory location for a given variable on every execution using a same binary image.
What could be the reason for the virtual address assigned for the local variable being different at runtime?
There is only one function and there is no chance to change the order of execution of the function and thereby to change the stack memory layout.
Result of running this program 4 times:
0x7fff181b4b2f
0x601034
0x7ffe34abd62f
0x601034
0x7ffe2813b98f
0x601034
0x7fffcef6b52f
0x601034
This is typically caused by address space layout randomization. It's a security technique meant to prevent certain types of attacks such as a buffer overflow.
Local variables in a hosted environment are typically stored on the stack. The virtual memory address of the stack changes in this case so that someone attempting to overrun a buffer and run arbitrary code won't be able to predict the address of where the malicious code will appear.