我试图了解内存分配如何适用于任何执行或编译的 C 代码。
我编写了以下 5 个单独的小代码,它们将帮助我理解内存分配过程。
段大小1.c
int main(){ printf("hellow world"); return 0; }
段大小2.c
//Adding uninitialized static int variable This would increase the size of BSS by 4 bytes. int main() { static int mystatic; printf("Hellow world"); return 0; }
段大小3.c
// Adding initialized static int variable, this would increase the size of initialized data // segment by 4 bytes. int main() { static int mystatic; static int mystatic1 = 100; printf("Hellow world"); return 0; }
段大小4.c
// Adding un-initialized global int variable, this would increase the size of BSS segment by 4 bytes. int myglobal; int main() { static int mystatic; static int mystatic1 = 100; printf("Hellow world"); return 0; }
段大小5.c
// Adding initialized global int variable, this would increase the size of data segment by 4 bytes. int myglobal; int myglobal2 = 500; int main() { static int mystatic; static int mystatic1 = 100; printf("Hellow world"); return 0; }
根据我的理解,如果我们编译上面的文件,那么在编译segment_size2.c后BSS大小应该增加4个字节,编译segment_size3.c后数据大小应该增加4个字节。但是当我点击 size 命令时,我得到了以下结果,
size segment_size1 segment_size2 segment_size3 segment_size4 segment_size5
text data bss dec hex filename
1217 560 8 1785 6f9 segment_size1
1217 560 8 1785 6f9 segment_size2
1217 564 12 1793 701 segment_size3
1217 564 12 1793 701 segment_size4
1217 568 16 1801 709 segment_size5
在这里我们可以清楚地看到编译segment_size3后bss和data段同时更新。这怎么可能?