hsy75的个人空间 https://blog.eetop.cn/vivilife [收藏] [复制] [分享] [RSS]

空间首页 动态 记录 日志 相册 主题 分享 留言板 个人资料

日志

[b][z]C/C++内存分配方式:堆和栈的区别:

已有 1284 次阅读| 2013-2-5 10:36 |个人分类:c/c++


内存分配方式

内存分配方式有三种:

[1] 从静态存储区域分配。内存在程序编译的时候就已经分配好,这块内存在程序的整个运行期间都存在。例如全局变量, static 变量。

[2] 在栈上创建。在执行函数时,函数内局部变量的存储单元都可以在栈上创建,函数执行结束时这些存储单元自动被释放。栈内存分配运算内置于处理器的指令集中 ,效率很高,但是分配的内存容量有限。

[3] 从堆上分配,亦称动态内存分配 。程序在运行的时候用 malloc  new 申请任意多少的内存,程序员自己负责在何时用 free  delete 释放内存。动态内存的生存期由程序员决定 ,使用非常灵活,但如果在堆上分配了空间,就有责任回收它,否则运行的程序会出现内存泄漏,频繁地分配和释放不同大小的堆空间将会产生堆内碎块。

2. 程序的内存空间

一个程序将操作系统分配给其运行的内存块分为 4 个区域,如下图所示。

代码区 (code area) 程序内存空间

全局数据区 (data area)

堆区 (heap area)

栈区 (stack area)

 

一个由 C/C++ 编译的程序占用的内存分为以下几个部分 ,

1 、栈区( stack     由编译器自动分配释放 ,存放为运行函数而分配的局部变量、函数参数、返回数据、返回地址等。其操作方式类似于数据结构中的栈。

2 、堆区( heap      一般由程序员分配释放, 若程序员不释放,程序结束时可能由 OS 回收 。分配方式类似于链表。

3 、全局区(静态区)( static )存放全局变量、静态数据、常量。程序结束后有系统释放

4 、文字常量区 常量字符串就是放在这里的。 程序结束后由系统释放。

5 、程序代码区存放函数体(类成员函数和全局函数)的二进制代码。

下面给出例子程序,

int a = 0; // 全局初始化区

char *p1; // 全局未初始化区

int main() {

int b; // 

char s[] = /"abc/"; // 

char *p2; // 

char *p3 = /"123456/"; //123456//0 在常量区, p3 在栈上。

static int c =0;// 全局(静态)初始化区

p1 = new char[10];

p2 = new char[20];

// 分配得来得和字节的区域就在堆区。

strcpy(p1, /"123456/"); //123456//0 放在常量区,编译器可能会将它与 p3 所指向的 /"123456/" 优化成一个地方。

}

 

堆与栈的比较

1 申请方式

stack: 由系统自动分配。 例如,声明在函数中一个局部变量 int b; 系统自动在栈中为 b 开辟空间。

heap: 需要程序员自己申请,并指明大小,在 C  malloc 函数, C++ 中是 new 运算符。

 p1 = (char *)malloc(10); p1 = new char[10];

 p2 = (char *)malloc(10); p2 = new char[20];

但是注意 p1  p2 本身是在栈中的。

2 申请后系统的响应

栈:只要栈的剩余空间大于所申请空间,系统将为程序提供内存,否则将报异常提示栈溢出。

堆:首先应该知道操作系统有一个记录空闲内存地址的链表 ,当系统收到程序的申请时,会遍历该链表,寻找第一个空间大于所申请空间的堆结点,然后将该结点从空闲结点链表中删除,并将该结点的空间分配给程序。

对于大多数系统,会在这块内存空间中的首地址处记录本次分配的大小,这样,代码中的 delete 语句才能正确的释放本内存空间。

由于找到的堆结点的大小不一定正好等于申请的大小,系统会自动的将多余的那部分重新放入空闲链表中。

3 申请大小的限制

栈:在 Windows  , 栈是向低地址扩展的数据结构,是一块连续的内存的区域。 这句话的意思是栈顶的地址和栈的最大容量是系统预先规定好的,在 WINDOWS 下,栈的大小是 2M (也有的说是 1M ,总之是一个编译时就确定的常数),如果申请的空间超过栈的剩余空间时,将提示 overflow 。因此,能从栈获得的空间较小。

堆:堆是向高地址扩展的数据结构,是不连续的内存区域。这是由于系统是用链表来存储的空闲内存地址的,自然是不连续的,而链表的遍历方向是由低地址向高地址。堆的大小受限于计算机系统中有效的虚拟内存。由此可见,堆获得的空间比较灵活,也比较大。

4 申请效率的比较

栈由系统自动分配,速度较快。但程序员是无法控制的 。

堆是由 new 分配的内存,一般速度比较慢,而且容易产生内存碎片 , 不过用起来最方便 。

另外,在 WINDOWS 下,最好的方式是用 VirtualAlloc 分配内存,他不是在堆,也不是栈,而是直接在进程的地址空间中保留一快内存,虽然用起来最不方便。但是速度快,也最灵活。

5 堆和栈中的存储内容

栈:在函数调用时,第一个进栈的是主函数中后的下一条指令(函数调用语句的下一条可执行语句)的地址,然后是函数的各个参数,在大多数的 C 编译器中,参数是由右往左入栈的 ,然后是函数中的局部变量。注意静态变量是不入栈的。

当本次函数调用结束后,局部变量先出栈,然后是参数,最后栈顶指针指向最开始存的地址,也就是主函数中的下一条指令,程序由该点继续运行。

堆:一般是在堆的头部用一个字节存放堆的大小。堆中的具体内容有程序员安排。

6 存取效率的比较

char s1[] = /"a/";

char *s2 = /"b/";

a 是在运行时刻赋值的;而 b 是在编译时就确定的;但是,在以后的存取中,在栈上的数组比指针所指向的字符串 ( 例如堆 ) 快。 比如:

int main(){

char a = 1;

char c[] = /"1234567890/";

char *p =/"1234567890/";

a = c[1];

a = p[1];

return 0;

}

 

对应的汇编代码

10: a = c[1];

00401067 8A 4D F1 mov cl,byte ptr [ebp-0Fh]

0040106A 88 4D FC mov byte ptr [ebp-4],cl

11: a = p[1];

0040106D 8B 55 EC mov edx,dword ptr [ebp-14h]

00401070 8A 42 01 mov al,byte ptr [edx+1]

00401073 88 45 FC mov byte ptr [ebp-4],al

 

第一种在读取时直接就把字符串中的元素读到寄存器 cl 中,而第二种则要先把指针值读到 edx 中,再根据 edx 读取字符,显然慢了。

7 小结

堆和栈的主要区别由以下几点:

1 、管理方式不同;

2 、空间大小不同;

3 、能否产生碎片不同;

4 、生长方向不同;

5 、分配方式不同;

6 、分配效率不同;

管理方式:对于栈来讲,是由编译器自动管理,无需我们手工控制;对于堆来说,释放工作由程序员控制,容易产生 memory leak 

空间大小:一般来讲在 32 位系统下,堆内存可以达到 4G 的空间,从这个角度来看堆内存几乎是没有什么限制的。但是对于栈来讲,一般都是有一定的空间大小的,例如,在 VC6 下面,默认的栈空间大小是 1M 。当然,这个值可以修改。

碎片问题:对于堆来讲,频繁的 new/delete 势必会造成内存空间的不连 续,从而造成大量的碎片,使程序效率降低。对于栈来讲,则不会存在这个问题,因为栈是先进后出的队列,他们是如此的一一对应,以至于永远都不可能有一个内 存块从栈中间弹出,在他弹出之前,在他上面的后进的栈内容已经被弹出,详细的可以参考数据结构。

生长方向:对于堆来讲,生长方向是向上的,也就是向着内存地址增加的方向;对于栈来讲,它的生长方向是向下的,是向着内存地址减小的方向增长。

分配方式:堆都是动态分配的 ,没有静态分配的堆。栈有 2 种分配方式:静态分配和动态分配。静态分配是编译器完成的,比如局部变量的分配。动态分配由 malloca 函数进行分配,但是栈的动态分配和堆是不同的,他的动态分配是由编译器进行释放,无需我们手工实现 。

分配效率:栈是机器系统提供的数据结构,计算机会在底层对栈提供支持:分配专门的寄存器存放栈的地址,压栈出栈都有专门的指令执行,这就决定了栈的效率比较高。堆则是 C/C++ 函数库提供的,它的机制是很复杂的,例如为了分配一块内存,库函数会按照一定的算法(具体的算法可以参考数据结构 / 操作系统)在堆内存中搜索可用的足够大小的空间,如果没有足够大小的空间(可能是由于内存碎片太多),就有可能调用系统功能去增加程序数据段的内存空间,这样就有机会分到足够大小的内存,然后进行返回。显然,堆的效率比栈要低得多。

从这里我们可以看到,堆和栈相比,由于大量 new/delete 的使用,容易造成大量的内存碎片;由于没有专门的系统支持,效率很低;由于可能引发用户态和核心态的切换,内存的申请,代价变得更加昂贵。所以栈在程序中是应用最广泛的,就算是函数的调用也利用栈去完成,函数调用过程中的参数,返回地址, EBP 和局部变量都采用栈的方式存放。所以,我们推荐大家尽量用栈,而不是用堆。

虽然栈有如此众多的好处,但是由于和堆相比不是那么灵活,有时候分配大量的内存空间,还是用堆好一些。

无论是堆还是栈,都要防止越界现象的发生(除非你是故意使其越界),因为越界的结果要么是程序崩溃,要么是摧毁程序的堆、栈结构,产生以想不到的结果。

4.new/delete  malloc/free 比较

 C++ 角度上说,使用 new 分配堆空间可以调用类的构造函数,而 malloc() 函数仅仅是一个函数调用,它不会调用构造函数,它所接受的参数是一个 unsigned long 类型。同样, delete 在释放堆空间之前会调用析构函数,而 free 函数则不会。

class Time{

public:

    Time(int,int,int,string);

    ~Time(){

       cout<</"call Time/'s destructor by:/"<<name<<endl;

    }

private:

    int hour;

    int min;

    int sec;

    string name;

};

Time::Time(int h,int m,int s,string n){

hour=h;

min=m;

sec=s;

name=n;

cout<</"call Time/'s constructor by:/"<<name<<endl;

}

int main(){

Time *t1;

t1=(Time*)malloc(sizeof(Time));

free(t1);

Time *t2;

t2=new Time(0,0,0,/"t2/");

delete t2;

system(/"PAUSE/");

return EXIT_SUCCESS;

}

 

结果:

call Time/'s constructor by:t2

call Time/'s destructor by:t2

从结果可以看出,使用 new/delete 可以调用对象的构造函数与析构函数,并且示例中调用的是一个非默认构造函数。但在堆上分配对象数组时,只能调用默认构造函数,不能调用其他任何构造函数


Not many programming languages support three storage types; even among the ones that do, very few allow the programmer to control precisely which type of storage will be used, for every variable and object. This diversity comes at a price: C++ memory management is hard to teach and learn, and it imposes more responsibility on the shoulders of the programmer. But this storage types diversity is also one of C++'s strengths. Without this diversity C++ wouldn't be C++ -- the C++ I like, that is.

Each of the three storage types of C++, static storageautomatic storage and free-store, affect the scope, lifetime and initialization of the objects and variables they host. Could C++ make do with a seemingly simpler memory model whereby all fundamental types are allocated on the stack, and user-defined types (except enums) are allocated exclusively on the free-store? This outwardly simplified memory model would make C++ programming much more complicated as a matter of fact. First, you wouldn't have the RAII idiom. Smart pointers, string classes, file stream objects, threads and mutexes wouldn't exist, unless they were redesigned from scratch in a way that would dictate a complex, error-prone usage protocol with the likelihood of serious performance degradation as a bonus. Secondly, you'd have to get used to a different type of C++ classes: classes that have no destructors at all. Admittedly, some of the RAII classes we use today are the result of the lack of an automatic garbage collector, so if the so-called simplified model is adopted, smart pointers won't be needed in the first place. The problem is that RAII classes aren't just smart pointers. Mutexes, threads and file stream objects allocate various types of resources (locks, file descriptors etc.) that a garbage collector doesn't reclaim. In fact, if you contrast how these classes are implemented in C++ with similar classes in other programming languages that have a built-in garbage collector you will notice that the non-C++ versions entail a more rigid, verbose and manual usage protocol. In these languages, the burden of releasing resources falls on the programmer each time a resource is used.

You could argue that a different simple memory model could be used instead of the simplistic model proposed above. Instead of sacrificing automatic storage for class objects, why not sacrifice the free-store? No one has ever proposed this seriously, but it's not an unprecedented model. In the early days of C (and I mean, very early!) many implementations didn't support malloc(). Under these constraints, programmers had to preallocate as much storage as they thought the program would consume -- at compile-time. Usually, this was done by allocating large char arrays with static (or automatic) storage type and then "allocating" memory from that pool dynamically (this is quite similar to how placement new is used today). There were two serious problems with that technique: either the application had preallocated too little memory, or it had preallocated too much. Remember: in those days memory was measures in bytes and kilobytes, not gigabytes and terabytes so the threshold was very low.

What about static memory? Seemingly, it's the least critical storage type of all three for end users but think what the cost of sacrificing it would be: you wouldn't have cin and cout or any other objects that are initialized automatically before main() starts. In addition, you wouldn't have local static objects. Worse yet, you wouldn't have static data members.

Nearly 40 years ago, Edsger Dijkstra criticized PL/1 for its size and diversity: "using PL/1 must be like flying a plane with 7000 buttons…" he wrote in his Turing Award paper. Contemporary C++ makes PL/1 look slim and parsimonious, but we're not in 1972. In 2008, a successful general-purpose programming language simply can't be cute and small; it must be flexible. Flexibility is achieved among other things by giving programmers a wider choice, at the right places -- exactly what C++ is all about. Is it only a coincidence that C++ flies more airplanes than does any other high-level programming language?





ref:
http://blog.csdn.net/rujielaisusan/article/details/4622197
http://www.informit.com/blogs/blog.aspx?uk=The-C-Features-I-Like-Most-Series-Static-Free-Store-and-Automatic-Storage-Types


点赞

评论 (0 个评论)

facelist

您需要登录后才可以评论 登录 | 注册

  • 关注TA
  • 加好友
  • 联系TA
  • 0

    周排名
  • 0

    月排名
  • 0

    总排名
  • 0

    关注
  • 2

    粉丝
  • 1

    好友
  • 2

    获赞
  • 14

    评论
  • 3241

    访问数
关闭

站长推荐 上一条 /2 下一条

小黑屋| 关于我们| 联系我们| 在线咨询| 隐私声明| EETOP 创芯网
( 京ICP备:10050787号 京公网安备:11010502037710 )

GMT+8, 2024-4-23 17:15 , Processed in 0.015918 second(s), 7 queries , Gzip On, Redis On.

eetop公众号 创芯大讲堂 创芯人才网
返回顶部