[英]Size of the stack and the heap
i read that the size of the stack in c in windows is 1 MB, and 8MB in linux, by default.我读到 c 中 windows 中的堆栈大小默认为 1 MB,linux 中为 8MB。 but that size can be changed.
但是这个尺寸是可以改变的。
1 - why would i use the heap when i am worried about size limits when i can change the stack to fit all the data? 1 - 当我担心大小限制时,我为什么要使用堆,而我可以更改堆栈以适应所有数据?
2 - what are the disadvantages of changing the limit of the stack and making it bigger? 2 - 改变堆栈的限制并使其更大的缺点是什么?
1 - why would i use the heap when i am worried about size limits when i can change the stack to fit all the data?
1 - 当我担心大小限制时,我为什么要使用堆,而我可以更改堆栈以适应所有数据?
It's not about size, it's about lifetime .这与大小无关,而与寿命有关。 Objects with
auto
storage duration (ie, allocated from the stack in most implementations) only exist for the lifetime of their enclosing scope or function.具有
auto
存储持续时间的对象(即,在大多数实现中从堆栈分配)仅在其封闭的 scope 或 function 的生命周期内存在。 That matters if you need something to persist across multiple function calls (such as a node in a list or tree).如果您需要在多个 function 调用(例如列表或树中的节点)中持久保存某些内容,这很重要。
Objects with allocated
storage duration (ie, allocated from the heap using malloc
, calloc
, or realloc
) exist until you explicitly deallocate them ( free
).具有已
allocated
存储持续时间的对象(即,使用malloc
、 calloc
或realloc
从堆中分配)一直存在,直到您显式取消分配它们( free
)。
2 - what are the disadvantages of changing the limit of the stack and making it bigger?
2 - 改变堆栈的限制并使其更大的缺点是什么?
You're making assumptions about what the underlying implementation can support, which can limit your ability to port code to other platforms (which may or may not be a concern for you).您正在对底层实现可以支持什么做出假设,这可能会限制您将代码移植到其他平台的能力(这可能会或可能不会让您担心)。 You're also trading frame size for stack depth - you'll run out of stack space faster if you set aside more space per function call, which can matter for deeply nested calls or recursive algorithms 1 .
您还在用帧大小换取堆栈深度 - 如果您为每个 function 调用留出更多空间,您将更快地耗尽堆栈空间,这对于深度嵌套调用或递归算法1可能很重要。
This is why the usual practice is to either allocate very large objects dynamically, or to make them static
.这就是为什么通常的做法是动态分配非常大的对象,或者使它们成为
static
。
Note: This answer is ment to be edited and extended with more dis/advantages...注意:这个答案需要编辑和扩展,有更多的缺点/优势......
Disadvantages of using the stack:使用堆栈的缺点:
Advantages of using the stack:使用堆栈的优点:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.