堆栈溢出 - 静态内存与动态内存

发布于 2024-09-27 17:16:12 字数 187 浏览 10 评论 0原文

如果在C/C++的main函数中写入int m[1000000];,则会出现堆栈溢出的运行时错误。相反,如果你写 vector; 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

安穩 2024-10-04 17:16:12

是的,向量本身是一个自动(堆栈)对象。但向量保存一个指向其内容的指针(内部动态数组),并且该指针将在堆上分配(默认情况下)。为了简化一点,您可以将 vector 视为在内部执行 malloc/reallocnew[] 调用(实际上它使用 分配器)。

编辑:正如我所指出的,自动变量在堆栈上分配,而 malloc 通常在堆上分配。每个的可用内存都是特定于平台甚至配置的,但可用堆栈内存通常更加有限。

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).

EDIT: 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.

时常饿 2024-10-04 17:16:12

堆栈内存的数量是有限的,因为它必须提前保留。然而,堆内存量通常会消耗操作系统施加的更高的限制,但“几乎”达到虚拟地址空间的限制(32 位机器为 2GB,64 位机器则更多)机器)。

您可以增加保留的堆栈空间量,通常作为链接器的设置。

The amount of stack memory is limited, because it has to be reserved in advance. However, the amount of heap memory will typically expend up to much higher limits imposed by your OS, but "nearly" reaching the limits of your virtual address space (2GB for a 32-bit machine, a whole lot more for a 64-bit machine).

You can increase the amount of reserved stack space, typically as a setting to your linker.

吲‖鸣 2024-10-04 17:16:12

int m[1000000] - 它将在堆栈上分配 1000000 个整数。由于堆栈有限,因此会抛出堆栈溢出运行时错误。

向量 m;然后 1000000 个元素的 push_back 正在工作,因为内部向量在堆上而不是在堆栈上分配内存。因此,在您的应用程序堆栈中,仅存在向量对象,因此它不会引发堆栈溢出运行时错误。

int m[1000000] - It will allocate the 1000000 ints on stack. as stack is limited so it will throw the stack overflow runtime error.

vector m; and then push_back of 1000000 elements are working because internally vector allocates the memory on heap not on stack. so in your application stack only the vector object is present so it is not throwing the stack overflow runtime error.

时光病人 2024-10-04 17:16:12

矢量对象本身在堆栈上;但在内部,它将根据需要从堆中分配内存来存储任意数量的元素。所以堆栈成本很小并且是固定的。

The vector object itself is on the stack; but internally it will allocate memory from the heap as needed to store an arbitary number of elements. So the stack cost is small and fixed for it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文