问题描述
以下代码在 2Gb 机器上运行时给我一个分段错误,但在 4GB 机器上运行.
int main(){int c[1000000];cout<<"完成\n";返回0;}
数组的大小只有 4Mb.c++中可以使用的数组的大小有限制吗?
您可能只是在这里遇到了堆栈溢出.数组太大,无法放入程序的堆栈区域;大多数主流桌面/服务器操作系统上的用户空间代码的堆栈增长限制通常为 8 MiB 或 1 MiB.(普通的 C++ 实现使用 asm 堆栈进行自动存储,即非static
局部变量数组.这使得在函数返回或异常通过它们传播时可以免费释放它们.)
如果你动态分配数组你应该没问题,假设你的机器有足够的内存.
int* array = new int[1000000];//可能抛出 std::bad_alloc
但请记住,这将需要您手动delete[]
数组以避免内存泄漏,即使您的函数通过异常退出也是如此.在现代 C++ 中强烈不鼓励手动新建/删除,更喜欢 RAII.>
更好的解决方案是使用 std::vector;数组
(cppreference).您可以为 1000000 个元素保留空间,如果您知道它将增长多少.或者甚至 resize
它来默认构造它们(即零初始化内存,不像你声明一个没有初始化器的普通 C 样式数组),比如 std::vector;数组(1000000)
当 std::vector
对象超出范围时,它的析构函数将为您释放存储空间,即使这是通过父函数捕获的子函数中的异常发生的.
The following code gives me a segmentation fault when run on a 2Gb machine, but works on a 4GB machine.
int main()
{
int c[1000000];
cout << "done\n";
return 0;
}
The size of the array is just 4Mb. Is there a limit on the size of an array that can be used in c++?
You're probably just getting a stack overflow here. The array is too big to fit in your program's stack region; the stack growth limit is usually 8 MiB or 1 MiB for user-space code on most mainstream desktop / server OSes. (Normal C++ implementations use the asm stack for automatic storage, i.e. non-static
local variables arrays. This makes deallocating them happen for free when functions return or an exception propagates through them.)
If you dynamically allocate the array you should be fine, assuming your machine has enough memory.
int* array = new int[1000000]; // may throw std::bad_alloc
But remember that this will require you to delete[]
the array manually to avoid memory leaks, even if your function exits via an exception. Manual new/delete is strongly discouraged in modern C++, prefer RAII.
A better solution would be to use std::vector<int> array
(cppreference). You can reserve space for 1000000 elements, if you know how large it will grow. Or even resize
it to default-construct them (i.e. zero-initialize the memory, unlike when you declare a plain C-style array with no initializer), like std::vector<int> array(1000000)
When the std::vector
object goes out of scope, its destructor will deallocate the storage for you, even if that happens via an exception in a child function that's caught by a parent function.
这篇关于大数组大小的分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!