为什么每次我 运行 相同的打印语句时内存地址都会改变?

Why does the memory address change every time I run the same print statement?

每次我 运行 完全相同的语句时,我都会在我的 C 程序中获得不同的内存位置。这不应该永远改变吗?是的,如果我将 &p 更改为 &x,它仍然会发生。我意识到这两个应该是不同的,但是当我重复 运行(未编译)程序以查看它的内存地址时会发生这种情况。

#include <stdio.h>
#include <string.h>


int main()
{
  int x = 30;
  int* p;
  p = &x;
  
  printf("%p \n", &p);
}

Proof

Why does the memory address change every time I run

因为您的系统使用 address space layout randomization (ASLR),特别是随机化堆栈放置。

在 Linux 上,您可以像这样为单个进程禁用 ASLR:

setarch -R ./a.out

运行 GDB下的程序也默认关闭了ASLR

I was taught that the memory address you designate for a variable would never change.

堆栈变量的地址实际上永远不会改变在程序的特定执行期间。它只能在不同的运行之间改变。