创建大型std :: array会导致segfault? [英] Creation of a large std::array causes segfault?

查看:120
本文介绍了创建大型std :: array会导致segfault?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个大的 std :: array 并用随机数据填充它。问题是如果我注释数组声明程序运行,则如果我声明std :: array程序segfaults(GDB表示它在自动启动.. 上存在segfaults)。

I want to create a large std::array and fill it with random data. The problem is that if I declare std::array program segfaults (GDB says it segfaults on auto start..) if i comment array declaration program runs.

这是SCSE:

#include <array>
#include <cstdint>
#include <iostream>
#include <chrono>

static const constexpr size_t size = 1E7;

int main(){

    auto start = std::chrono::high_resolution_clock::now();
    std::array<uint16_t, size> random_data;
    // Here I want to fill random_data with random numbers to avoid 
    // filling memory twice
    auto end = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double> elapsed = end-start;
    std::cout << "Elapsed sec " << elapsed.count() << std::endl;

}

它是使用在gcc中编译的-std = gnu ++ 11 在GNU / Linux上。

It is compiled in gcc using -std=gnu++11 on GNU/Linux.

推荐答案

您的 array 位于堆栈中,其成员也位于堆栈中,基础数组。但是您的计算机上的堆栈可能不大四十兆字节,因此您的程序会崩溃。

Your array lies on the stack, and so does its member, the underlying array. But the stack on your machine is presumably not forty megabytes large, so your program crashes.

使用 vector

std::vector<std::uint16_t> random_data(size);

或者,如果您想避免不必要的初始化并且不需要动态改变大小,请使用 unique_ptr 持有一个数组。

Or, if you want to avoid unnecessary initialization and don't need dynamic change in size, use a unique_ptr holding an array.

std::unique_ptr<std::uint16_t[]> random_data( new std::uint16_t[size] );

演示

这篇关于创建大型std :: array会导致segfault?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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