5
21
2014
2

C/C++中堆、栈、自由存储区、全局/静态存储区、常量存储区

本文的内容来自

http://www.cnblogs.com/hanyonglu/archive/2011/04/12/2014212.html

 

在C/C++中,内存分为5个区,分别是堆、栈、自由存储区、全局/静态存区、常量存储区。

栈:由编译器在需要的时候分配,不需要时自动清除的存储区。里面的变量为局部变量、函数参数等。

堆:由new分配的内存块,释放是程序员代码手动的。delete来释放new的东西

自由存储区:malloc分配的内存块,和堆类似,不同处在于用free结束生命

全局/静态存储区:全局变量和静态变量。内存在程序编译的时候就已经分配好,这块内存在整个程序运行的期间都在

常量存储区:里面存放常量

以下看一个例子:

void f(){ int *p = new int[5];}

上面这个语句就调用了栈和堆,new 对应的为堆中分配的空间、指针p为栈中的存储区间。


下面重点讨论一下栈和堆的区别。

管理方式--栈:编译器自动管理,无需手动控制;堆:释放工作手动

空间大小--栈:默认大小较小,大小约为1M ;堆:32为系统,内存可达到4G。

碎片问题--栈,先进后出,不存在空间碎片;堆:频繁的new/delete会造成内存空间不连续

生长方向--栈,向内存地址小的方向增长;堆:向内存地址大的方向增长

分配方式--栈:静态和动态分配,静态分配编译器完成:如局部变量的分配。动态分配,如alloc函数,但其由编译器自动释放;堆:只能动态分配,new 需要手动释放。

分配效率--栈:机器系统提供的数据结构,计算机在底层对栈提供支持,效率高;堆:库函数提供,故机制较为复杂,效率偏低。

 

Category: 编程理解 | Tags: | Read Count: 3939
Avatar_small
NCERT History Sample 说:
2022年9月29日 14:28

By knowing about history we may get aware of what kind of result we gain by doing what kind of things either good or evil. It inspires the students to understand their successes and failures. NCERT History Sample Paper Class 9 history shows the past patterns of behaviour or events and their outcome, which can help us avoid similar outcomes in the future. NCERT has introduced topic-wide study & learning material for all class 9th standard students for History.NCERT has introduced topic-wide study & learning material for all class 9th standard students for History.By knowing about history we may get aware of what kind of result we gain by doing what kind of things either good or evil. It inspires the students to understand their successes and failures.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter

Host by is-Programmer.com | Power by Chito 1.3.3 beta | Theme: Aeros 2.0 by TheBuckmaker.com