创建一个包含300万个元素的双数组

时间:2015-10-23 16:46:01

标签: c++ arrays segmentation-fault

我正在尝试创建一个包含300万个随机元素的双精度数组:

#include <iostream>
#include <cstdlib>
#include <random>
#include <ctime>

using namespace std;

int main(int argc, const char * argv[]) {

    // generating random numbers
    mt19937 rng_engine(0); // seed = 0
    uniform_real_distribution<double> dist2(0,10);    

    clock_t begin = clock();

    // create a random 2d array 1 million x 3
    double coords[1000000][3];
    for (int i=0; i<1000000; i++) {
        for (int j= 0; j<3; j++) {
            coords[i][j] = dist2(rng_engine);
            //cout << "i = " << i << ", j = " << j << ", val = " << coords[i][j] << endl;
        }
    }

    clock_t end = clock();
    double elapsed = double(end - begin) / CLOCKS_PER_SEC;

    cout << "elapsed: " << elapsed << endl;

    return 0;
}

当我尝试在Xcode中运行时,我得到EXC_BAD_ACCESS (code=2, address=0x7fff5e51bf9c)。我试图编译它并在命令行中运行它,它给了Segmentation fault: 11。当我将数组大小更改为[100000][3]时,使元素数量达到300,000,代码就会运行。我不明白为什么有300万双打是一个问题。数组大小不是24 MB吗? (8字节* 3,000,000 = 24 MB)我缺少什么?

4 个答案:

答案 0 :(得分:2)

你几乎肯定会溢出堆栈。

避免这种情况的明显选择是制作数组staticmain中的数据确实变化不大,但通常以不同的方式分配)或(通常)更好)改为使用std::vector

答案 1 :(得分:1)

double coords[1000000][3];

这对于堆栈来说太大了。请改用std::vector

std::vector<double> coords(1000000 * 3); // flatten vector

std::vector<std::vector<double>> coords(1000000, std::vector<double>(3));

答案 2 :(得分:0)

您需要使用malloccalloc动态分配大型数组,因为声明的变量存储在堆栈中,而堆栈的大小有限。 malloccalloc代替堆空间。

答案 3 :(得分:0)

24 mb远高于典型的堆栈大小。你正在离开你的堆栈。

尝试动态分配或使用容器类(它将在内部动态分配)。