为什么相同的变量在不同的运行中得到不同的虚拟地址?

| 我需要知道项目中变量(尤其是堆变量)的虚拟地址。变量的指针值实际上是其虚拟地址。我的理解是,同一变量的虚拟地址在不同运行时应相同。我编写了以下简单的代码来证明自己的想法,但事实证明这是错误的,
#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代码,每个进程仅生成完全相同的变量。而且针对不同进程的相同变量具有不同的指针值,这与我预期的不同。 有人可以向我解释吗? 谢谢,     
已邀请:
        不能保证变量的地址在两次运行之间保持不变。现代操作系统尝试更改程序加载到的地址以及堆和堆栈的地址,以防止发生这种情况。他们这样做是因为它使攻击者更难利用某些类型的错误。 具体来说,在您的情况下,您正在查看的变量是在堆上分配的指针。绝对没有理由期望在堆上分配两次内存会产生两次相同的地址。     
        这个问题类似于我的问题:Linux下的伪随机堆栈指针? 出于安全原因,所有操作都已完成,如awser中的链接所述。     

要回复问题请先登录注册