C ++堆栈数组限制? [英] C++ stack array limit?

查看:143
本文介绍了C ++堆栈数组限制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我运行一些代码,可能指出我不明白堆和堆栈之间的区别。下面我有一些示例代码,其中我或者声明一个数组在堆栈或1234567元素堆。两者都工作。

I'm running some code which may be pointing out I don't understand the difference between the heap and stack that well. Below I have some example code, where I either declare an array on the stack or the heap of 1234567 elements. Both work.

int main(int argc, char** argv){

  int N = 1234567;

  int A[N];

  //int* A = new int[N];

}

但是如果我们取N为12345678, seg fault with int A [N],而堆声明仍然可以正常工作。 (我使用g ++ O3 -std = c ++ 0x如果这很重要)。这是什么疯狂?

But if we take N to be 12345678, I get a seg fault with int A[N], whereas the heap declaration still works fine. (I'm using g++ O3 -std=c++0x if that matters). What madness is this? Does the stack have a (rather small) array size limit?

推荐答案

堆通过malloc和co进行动态分配。堆栈随着在运行程序的过程中进行的每个函数调用而增长。返回地址,参数,局部变量通常存储在堆栈中(除了在某些处理器架构中,其中的一些被存储在寄存器中)。也可以(但不常见)动态分配堆栈空间。

The heap grows dynamically with allocation through malloc and co. The stack grows with each function call made in the course of running a program. The return address, arguments, local variables are usually stored in the stack (except that in certain processor architectures a handful of these are stored in registers instead). It is also possible (but not common) to allocate stack space dynamically.

堆和堆栈竞争使用相同的内存。你可以思考一个从左到右,另一个从右到左。有可能,如果不加检查,它们可能发生碰撞。堆叠通常被限制生长超过某一界限。这是相对较小的,因为它预计它将仅使用几个字节的大多数调用,只有几个堆栈级别将被使用。该限制很小,但对于大多数任务来说是足够的。您可以通过更改构建设置(而不是Linux ELF二进制文件)或通过调用setrlimit来扩展此限制。操作系统还可以施加一个您可以更改的限制。可能有软和硬限制(http://www.nics.tennessee.edu/node/327)。

The heap and the stack compete for the use of the same memory. You can think on one growing left to right and the other growing right to left. There is a possibility that, if left unchecked, they may collide. The stack is typically restrained from growing beyond a certain bound. This is relatively small because it is expected that it will use only a few bytes for most calls and only a few stack levels will be used. The limit is small but sufficient for most tasks. You can expand this limit by changing your build settings (not for Linux ELF binaries though) or by calling setrlimit. The OS may also impose a limit which you can change. There may be soft and hard limits (http://www.nics.tennessee.edu/node/327).

有关限制的更多细节不属于问题的范围。底层是堆栈是有限的,它是相当小,因为它与堆的实际内存竞争,对于典型的应用程序,它不需要更大。

Going into greater detail about the limits falls outside the scope of the question. The bottomline is that the stack is limited and it is quite small because it competes with the heap for actual memory and for typical applications it need not be bigger.

http://en.wikipedia.org/wiki/Call_stack

这篇关于C ++堆栈数组限制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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