Why same variable got different virtual addresses at different runs?
I need to know the virtual address of the variables (the heap variable, in particular) in my project. The pointer value of the variable is actually its virtual address. My understanding is that the Virtual Address of the same variable should the same at different runs. I wrote the following simple code to prove my thoughts, but it turns out to be wrong,
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
int node=0;
char* buffer;
int i;
printf("Hello World from Node %d the vm of i is %p and %ld \n",node, &i,&i);
buffer = (char*)malloc(sizeof(char)*1024*1024*300);
for(i = 0; i < 1024*1024*300; i++){
buffer[i] = (char)1;
}
printf("I am in %d and the vm of buffer is %p:%ld \n",node, buffer,buffer);
return 0;
}
But I got different pointer values for different runs as follows,
-bash-4.0$ gcc singletest.c
-bash-4.0$ ./a.out
Hello World from Node 0 the vm of i is 0x7fffb87a8e00 and 140736288427520
I am in 0 and the vm of buffer is 0x7fb05dfcf010:140395467829264
-bash-4.0$ ./a.out
Hello World from Node 0 the vm of i is 0x7fffec2856f0 and 140737155454704
I am in 0 and the vm of buffer is 0x7f5888c54010:140018228477968
-bash-4.0$ ./a.ou开发者_StackOverflowt
Hello World from Node 0 the vm of i is 0x7fff1f44a780 and 140733717981056
I am in 0 and the vm of buffer is 0x7fbea3b91010:140456767328272
I also wrote a simple MPI code that each process simply generates exactly the same variable. And the same variable for different processes have the different pointer values, which is not as I expected.
Can any one explain this to me ? Thanks,
There's no guarantee that a variable's address would stay the same between runs. Modern operating systems try to change the address programs are loaded into and the heap and stack's addresses, exactly to prevent that from happening. They do this because it makes it harder for attackers to exploit certain classes of bugs.
Specifically, in your case, the variable you're looking at is a pointer allocated on the heap. There's absolutely no reason to expect that allocating memory twice on the heap would produce the same address twice.
This question is similar to one of mine: Pseudo-random stack pointer under Linux?
It's all done for sercurity reasons, as the link in the awser describes.
精彩评论