一、一个由C/C++编译到程序占用的内存分为以下几个部分:
1、栈区(stack)——由编译器自动分配释放,在不需要的时候自动清除。用于存放函数的参数、局部变量等。操作方式类似数据结构中的栈(后进先出)。
2、堆区(heap)——一般由程序员分配释放,若程序员分配后不释放,程序结束后可能由OS回收。不同于数据结构中的堆,分配方式有些类似链表。
3、全局区(静态区)——全局变量和静态变量存储在这里。程序结束后由系统释放。在以前到C语言中,全局变量又细分为初始化的(DATA段)和未初始化到(BSS段),在C++里已经没有这个区分了,它们共同占用同一块内存区。
4、常量存储区——常量字符串就存放在这里。一般不允许修改。程序结束后由系统释放。
5、代码区——存放函数体的二进制代码。
示意图如下:
|----------------------| 高地址
| 栈区(Statk) | -->向下增长
|----------------------|
| 堆区(Heap) | -->向上增长
|----------------------|
| 未初始化(BSS) |
|----------------------|
| 初始化(Data) |
|----------------------|
| 常量存储区 |
|----------------------|
| 正文段(Text) |
|----------------------| 低地址
附上另一副图:
二、一段经典的例子程序,帮助理解
1 //main.c 2 #include<string.h> 3 #include<stdlib.h> 4 int a = 0;//全局初始化区 5 char *p1; //全局未初始化区 6 int main() 7 { 8 int b = 0;//栈 9 char s[] = "abc";//栈10 char *p2;//栈11 char *p3 = "123456";//123456 在常量区,p3在栈上12 static int c = 0;//全局初始化区13 p1 = (char *)malloc(10);14 p2 = (char *)malloc(20);//分配得到到空间在堆区15 strcpy(p1,"123456");//123456 放在常量区16 //编译器可能会将它与p3所指向的123456 优化成一个地方17 return 0;18 }
Ubuntu下用gcc生成汇编看看,命令:
gcc -S main.c
打开目录下到main.s,汇编代码如下:
1 .file "main.c" 2 .globl a 3 .bss ;大概看出这是BSS段声明 4 .align 4 5 .type a, @object 6 .size a, 4 7 a: 8 .zero 4 9 .comm p1,4,4 ;这里大概就是DATA段10 .section .rodata11 .LC1:12 .string "123456" ;常量存储区13 .LC0:14 .string "abc" ;栈区15 .text ;代码段16 .globl main17 .type main, @function18 main:19 pushl %ebp20 movl %esp, %ebp ;保存esp现场在ebp中,ebp保存在栈中。Linux下mov a,b是把a赋值给b,与Win下相反21 andl $-16, %esp ;这个貌似是为了对齐神马的22 subl $32, %esp ;分配栈区,用于存放局部变量等。栈区向下增长,因此是减23 movl $0, 28(%esp) ;esp+28,自然是int b = 0;这句24 movl .LC0, %eax25 movl %eax, 24(%esp) ;char s[] = "abc";26 movl $.LC1, 16(%esp);char *p3 = "123456"这句,esp+20是p2,char *p2这句被优化到后面30-32去了27 movl $10, (%esp)28 call malloc29 movl %eax, p1 ;p1 = (char *)malloc(10);30 movl $20, (%esp)31 call malloc32 movl %eax, 20(%esp) ;p2 = (char *)malloc(20);33 movl $.LC1, %edx34 movl p1, %eax35 movl $7, 8(%esp)36 movl %edx, 4(%esp)37 movl %eax, (%esp)38 call memcpy ;strcpy(p1,"123456")这句,“123456 ”,用的LC1,和上面用的一个39 movl $0, %eax ;return 0;40 leave41 ret42 .size main, .-main43 .local c.197444 .comm c.1974,4,445 .ident "GCC: (Ubuntu/Linaro 4.4.4-14ubuntu5) 4.4.5"46 .section .note.GNU-stack,"",@progbits
用空再试试-o -o2神马的。还有Win下到反汇编。
三、回忆几个题
1、常量存储区的优化
1 #include<stdio.h> 2 int main() 3 { 4 char str1[] = "hello world"; 5 char str2[] = "hello world"; 6 char* str3 = "hello world"; 7 char* str4 = "hello world"; 8 if(str1 == str2) 9 printf("str1 and str2 are same.n");10 else11 printf("str1 and str2 are not same.n");12 13 if(str3 == str4)14 printf("str3 and str4 are same.n");15 else16 printf("str3 and str4 are not same.n");17 return 0;18 }//str1 and str2 are not same.//str3 and str4 are same.
char s[]="abc";
原文链接: https://www.cnblogs.com/rusty/archive/2011/03/21/1990667.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/22587
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!