写一个很简单的 c++ 代码,打印一些“地址”, 也就是变量、函数的“存储位置”:当程序被加载到内存后,它们具体是存在哪里,可以用精确的数值来表示,这就是内存地址。
https://godbolt.org/z/Ghh9ThY5Y
#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
第二个例子
https://godbolt.org/z/vEW9EdYsh
#include <stdio.h>
void func()
{
int c = 4;
int*d = &c;
printf("&c=%p\n", &c);
printf("&d=%p\n", &d);
}
int main()
{
int a = 4;
int*b = &a;
printf("&a=%p\n", &a);
printf("&b=%p\n", &b);
func();
return 0;
}
ASM generation compiler returned: 0
Execution build compiler returned: 0
Program returned: 0
&a=0x7ffcf64bee78
&b=0x7ffcf64bee70
&c=0x7ffcf64bee4c
&d=0x7ffcf64bee40