我需要知道項目中變量的虛擬地址(尤其是堆變量)。變量的指針值實際上是其虛擬地址。我的理解是,同一個變量的虛擬地址應該在不同的運行時相同。我寫了下面簡單的代碼來證明我的想法,但事實證明是錯誤的,爲什麼同一個變量在不同的運行時得到不同的虛擬地址?
#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;
}
但我得到了不同的運行不同的指針值如下,
-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.out
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
我也寫了一個簡單MPI代碼,每個進程只生成完全相同的變量。不同進程的相同變量具有不同的指針值,這不是我所期望的。
任何人都可以向我解釋這一點嗎? 謝謝,
謝謝!如果地址隨機化被禁用,你認爲我有兩次運行的指針值可能相同嗎?即使是堆變量?謝謝, –
我嚴重懷疑你可以依靠這個。我不會推薦它。 –
我只需按照http://stackoverflow.com/questions/1921485/pseudo-random-stack-pointer-under-linux中的說明禁用隨機化。堆變量具有用於不同運行的固定虛擬地址。 –