堆栈溢出 - 静态内存与动态内存 [英] Stack overflow - static memory vs. dynamic memory
问题描述
如果在C / C ++的main函数中写入 int m [1000000];
,它将得到堆栈溢出的运行时错误。相反,如果你写 vector< int> m;
然后push_back 1000000元素,它会运行正常。
If you write int m[1000000];
inside the main function of C/C++, it will get a runtime error for stack overflow. Instead if you write vector<int> m;
and then push_back 1000000 elements there, it will run fine.
我很好奇为什么会发生这种情况。他们都是本地内存,不是吗?提前致谢。
I am very curious about why this is happening. They both are local memory, aren't they? Thanks in advance.
推荐答案
是的,向量本身是一个自动(堆栈)对象。但是该向量包含一个指向其内容的指针(内部动态数组),并且将在堆上分配(默认情况下)。为了简化一点,你可以认为向量
是做 malloc
/ realloc
或 new []
内部调用(实际上它使用 allocator )。
Yes, the vector itself is an automatic (stack) object. But the vector holds a pointer to its contents (an internal dynamic array), and that will be allocated on the heap (by default). To simplify a little, you can think of vector
as doing malloc
/realloc
or new[]
calls internally (actually it uses an allocator).
编辑:我注意到,自动变量分配在堆栈上,而 malloc
一般在堆上分配。每个可用的内存是平台甚至配置特定的,但是可用的堆栈内存通常更受限制。
As I noted, automatic variables are allocated on the stack, while malloc
generally allocates on the heap. The available memory for each are platform and even configuration-specific, but the available stack memory is typically much more limited.
这篇关于堆栈溢出 - 静态内存与动态内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!