为什么C ++数组创建会导致分段错误? [英] Why does C++ array creation cause segmentation fault?

查看:150
本文介绍了为什么C ++数组创建会导致分段错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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];
}

小于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]

我不太了解问题所在.我曾尝试搜索类似的问题,但仍然不明白.我还尝试在 ideone 中运行它,并且效果很好.因此,我认为这可能与我的IDE eclipse有关. (不确定)

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)

推荐答案

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

在堆栈上分配std::set43309个副本.在Windows上,默认堆栈大小通常为1MB.从观察到的结果来看,实现的std::set可能每个使用大约24个字节,从而导致数组使用1,039,392字节,这比可用的堆栈内存还要多.

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.

在所有平台上堆栈都很小,Mac和Linux通常具有8MB堆栈.它们仅设计用于局部变量,函数参数,已保存的寄存器等的少量分配.应在堆上进行较大的分配.

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.

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

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

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

这篇关于为什么C ++数组创建会导致分段错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆