变量的内存布局
写段代码测试一下变量的内存分布:
#include <cstdlib> #include <cstdio> char bss_global; char rw_data_global = 0; const char ro_data1 = 0; static char rw_data_static = 0; int main() { static char bss_static; char stack1; char stack2[] = {"Hello world!"}; const char stack3 = 0; const char* ro_data2 = "Hello world!"; char* heap1 = (char*)malloc(10*sizeof(char)); char* heap2 = new char(0); printf("---------------------------\n"); printf("stack: %.8p\n", stack2); printf("stack: %.8p\n", &stack3); printf("stack: %.8p\n", &stack1); printf("---------------------------\n"); printf("heap: %.8p\n", heap2); printf("heap: %.8p\n", heap1); printf("---------------------------\n"); printf("bss: %.8p\n", &bss_static); printf("bss: %.8p\n", &bss_global); printf("---------------------------\n"); printf("read write data: %.8p\n", &rw_data_static); printf("read write data: %.8p\n", &rw_data_global); printf("---------------------------\n"); printf("read only data: %.8p\n", &ro_data1); printf("read only data: %.8p\n", ro_data2); printf("---------------------------\n"); printf("text: %.8p\n", main); printf("text: %.8p\n", malloc); printf("text: %.8p\n", printf); printf("---------------------------\n"); free(heap1); delete heap2; return 0; }
Linux上结果如下:
--------------------------- stack: 0xbfe1cdbf stack: 0xbfe1cdbe stack: 0xbfe1cdbd --------------------------- heap: 0x08bf8018 heap: 0x08bf8008 --------------------------- bss: 0x0804a037 bss: 0x0804a034 --------------------------- read write data: 0x0804a036 read write data: 0x0804a035 --------------------------- read only data: 0x08048923 read only data: 0x08048870 --------------------------- text: 0x08048594 text: 0x080484b0 text: 0x08048490 ---------------------------
Windows上结果如下:
--------------------------- stack: 001BFDD4 stack: 001BFDD3 stack: 001BFDD2 --------------------------- heap: 003CB320 heap: 003CB308 --------------------------- bss: 0104CDE3 bss: 0104CDE0 --------------------------- read write data: 0104CDE2 read write data: 0104CDE1 --------------------------- read only data: 01049148 read only data: 0104915C --------------------------- text: 01041000 text: 010412CE text: 01041375 ---------------------------
为什么bss_static在rwdata之上?涉及到static变量的生命周期:bss_global在程序启动时分配,而main函数运行到该代码处才为bss_static分配空间。