Why does C++ array creation cause segmentation fault?

后端 未结 1 1381
误落风尘
误落风尘 2021-01-27 09:32

I have a program that needs an array of set>. For the small value of array size, the program works well. When the program runs into large a

相关标签:
1条回答
  • 2021-01-27 10:10
    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);
    
    0 讨论(0)
提交回复
热议问题