为什么会你想在堆上,而不是堆栈分配内存? [英] Why would you ever want to allocate memory on the heap rather than the stack?

查看:202
本文介绍了为什么会你想在堆上,而不是堆栈分配内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:

  <一href=\"http://stackoverflow.com/questions/102009/when-is-it-best-to-use-a-stack-instead-of-a-heap-and-vice-versa\">When它是最好使用堆栈,而不是一个堆,反之亦然?

我读过一些关于堆VS堆栈中的其他问题,但他们似乎更专注于堆/栈做的,而不是你为什么会使用它们。

I've read a few of the other questions regarding the heap vs stack, but they seem to focus more on what the heap/stack do rather than why you would use them.

在我看来,这堆栈分配几乎总是会pferred,因为它的速度更快(只是移动堆栈指针VS寻找堆自由空间)$ P $,而不必手动自由分配内存时你用它做。我可以看到使用堆分配的唯一原因是,如果你想在一个函数创建一个对象,然后用它之外的功能范围,因为堆栈分配的内存在函数返回后自动分配。

It seems to me that stack allocation would almost always be preferred since it is quicker (just moving the stack pointer vs looking for free space in the heap), and you don't have to manually free allocated memory when you're done using it. The only reason I can see for using heap allocation is if you wanted to create an object in a function and then use it outside that functions scope, since stack allocated memory is automatically unallocated after returning from the function.

有其他原因使用堆分配而不是堆栈分配,我不知道呢?

Are there other reasons for using heap allocation instead of stack allocation that I am not aware of?

推荐答案

有几个原因:


  • 的主要原因之一是,随着堆分配,你有在对象的生命周期中最灵活的控制(从的malloc / 释放calloc 免费);

  • 堆栈空间通常比堆空间,至少在默认配置更有限的资源;

  • 来分配堆空间的故障,可以正常处理,而运行的堆栈空间往往是不可恢复的。

  • The main one is that with heap allocation, you have the most flexible control over the object's lifetime (from malloc/calloc to free);
  • Stack space is typically a more limited resource than heap space, at least in default configurations;
  • A failure to allocate heap space can be handled gracefully, whereas running out of stack space is often unrecoverable.

如果没有灵活的对象的生命周期,有用的数据结构,例如二叉树和链表实际上是不可能写出

Without the flexible object lifetime, useful data structures such as binary trees and linked lists would be virtually impossible to write.

这篇关于为什么会你想在堆上,而不是堆栈分配内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆