写一个很简单的 c++ 代码,打印一些“地址”, 也就是变量、函数的“存储位置”:当程序被加载到内存后,它们具体是存在哪里,可以用精确的数值来表示,这就是内存地址。

https://godbolt.org/z/Ghh9ThY5Y
CPU眼里的C/C++:1.2 查看变量和函数在内存中的存储位置-LMLPHP

#include <stdio.h>
#include <stdlib.h>

char a[] = "password";

int main()
{
    int b = 2;
    int* c = (int*)malloc(4);
    *c = 0x11223344;
    printf("%p, %p, %p, %p\n", &a, &b, c, main);
}
ASM generation compiler returned: 0
Execution build compiler returned: 0
Program returned: 0
0x404038, 0x7fff019b0e64, 0x2377eb0, 0x401140

对应的内存地址,按从高到低,顺如如下(不同的GLIBC版本,得到的具体值会有差异,但是整体趋势是固定的:stack地址从高往低增长(🔽), .text 和 .data 在地址比较低的地方, heap 则从地址较低的地方往地址较高的地方增长(🔼)

b             (0x404038)    // stack
c             (0x2377eb0)  // heap
a             (0x404038)  // .data
main          (0x401140) // .text
10-25 00:25