Why does C++ array creation cause segmentation fault?

♀尐吖头ヾ 提交于 2020-01-11 12:55:14

问题


I have a program that needs an array of set<vector<bool>>. For the small value of array size, the program works well. When the program runs into large array size, it exits with exit code -1073741571.

So, I debug the code and find when it occurs. Below is the simplest code that reproduces my error.

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

Values smaller than 43309 cause no error. I try debugging and it shows

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]

I don't really understand what is the problem. I have tried searching similar questions but still I don't get it. I also tried running it in ideone and it works fine. So, I think it might be related to my IDE, eclipse. (not sure)


回答1:


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

allocates 43309 copies of std::set on the stack. On windows the default stack size is normally 1MB. Judging by your observed results your implementation's std::set probably uses around 24 bytes each resulting in your array using 1,039,392 bytes which is more than the available stack memory.

Stacks are small on all platforms, Mac and Linux typically have 8MB stacks. They are only designed to be used for small allocations of local variables, function parameters, saved registers etc. Large allocations should be done on the heap.

The simplest way to do this is using std::vector, it manages the heap allocation for you:

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


来源:https://stackoverflow.com/questions/57850276/why-does-c-array-creation-cause-segmentation-fault

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!