调整大型结构向量大小时出现分段错误 [英] segmentation fault on resizing a vector of large structures

查看:39
本文介绍了调整大型结构向量大小时出现分段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码产生了一个分段错误,我不明白为什么.下面的代码使用一个向量来存储多个大型结构体,但该代码不会运行并生成分段错误.我不明白为什么.我的理解是 vector resize 在堆中分配内存,所以这不应该是堆栈溢出问题.我的系统具有非常大的物理内存 (256 GB),并且代码以 64 位模式编译,因此仅分配 40 MB 应该不是问题.有什么想法吗?

The code below is generating a segementation fault, and I do not understand why. The code below uses a vector to store multiple large strucutres, but the code does not run and generates a segmentation fault. I don't understand why. My understanding is that vector resize allocates memory in heap so this shouldn't be a stack overflow problem. My system has very large physical memory (256 GB) and the code is compiled in 64 bit mode so allocating just 40 MB should not be a problem. Any ideas?

非常感谢您,

#include <vector>

using namespace std;

typedef struct _tmp_t {
    int a_data[10*1000*1000];/* large array */
} tmp_t;

int main( void ) {
    vector<tmp_t> v_tmp;

    v_tmp.resize( 1 );

    return 0;
}

推荐答案

问题是调用 std::vector::resize 会创建临时对象(注意它有第二个参数默认T());这些驻留在堆栈中.所以你的筹码很严重.

The problem is that calling std::vector::resize will create temporary objects (note that it has a second argument that defaults to T()); these reside on the stack. So you're blowing your stack.

这篇关于调整大型结构向量大小时出现分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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