【发布时间】:2011-06-24 22:13:38
【问题描述】:
我需要知道我项目中变量(尤其是堆变量)的虚拟地址。变量的指针值实际上就是它的虚拟地址。我的理解是同一变量的虚拟地址在不同的运行中应该相同。我写了以下简单的代码来证明我的想法,但结果证明是错误的,
#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 代码,每个进程只生成完全相同的变量。而且不同进程的同一个变量指针值不同,这和我想象的不一样。
谁能给我解释一下? 谢谢,
【问题讨论】:
标签: pointers virtual memory-address