为什么 C++ 数组创建会导致分段错误?

Why does C++ array creation cause segmentation fault?

我有一个程序需要 set<vector<bool>> 的数组。对于较小的数组大小值,该程序运行良好。当程序遇到大数组时,它会以退出代码 -1073741571 退出。

所以,我调试代码并找到它何时发生。下面是重现我的错误的最简单的代码。

#include <iostream>
#include <cmath>
#include <omp.h>
#include <set>
#include <vector>
using namespace std;
int main() {
    set<vector<bool>> C[43309];
}

小于 43309 的值不会导致错误。我尝试调试,它显示

Thread 1 received signal SIGSEGV, Segmentation fault.
0x00007fff0d17ca99 in ntdll!memset () from C:\WINDOWS\SYSTEM32\ntdll.dll
[Thread 17616.0x3f64 exited with code 3221225725]
[Thread 17616.0x342c exited with code 3221225725]
[Inferior 1 (process 17616) exited with code 030000000375]

我不太明白问题出在哪里。我试过搜索类似的问题,但我还是不明白。我还在 ideone 中尝试了 运行 它并且工作正常。所以,我想这可能和我的IDE,eclipse有关。 (不确定)

set<vector<bool>> C[43309];

在堆栈上分配 43309std::set 的副本。在 windows 上,默认堆栈大小通常为 1MB。根据您观察到的结果判断,您的实现的 std::set 可能使用大约 24 个字节,每个导致您的数组使用 1,039,392 字节,这比可用的堆栈内存多。

堆栈在所有平台上都很小,Mac 和 Linux 通常有 8MB 堆栈。它们仅设计用于局部变量、函数参数、保存的寄存器等的小型分配。大型分配应在堆上完成。

最简单的方法是使用 std::vector,它会为您管理堆分配:

auto C = vector<set<vector<bool>>>(43309);