巨大数组中的访问冲突? [英] Access violation in huge array?

查看:31
本文介绍了巨大数组中的访问冲突?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

constexpr auto array_size = 50000000; 
double M[array_size][2][20]= { };


int main()
{
    for (int n = 0; n < array_size; n++)
        printf("%d %f\n",n, M[n][0][0]);
}

当 n 打印到大约 150 时,这个程序崩溃了.

When n printed to about 150, this program crashed.

我也看到了 M[90] 的异常值,就像 386721638216381263812386113....

I also see abnormal value in M[90], it is like 386721638216381263812386113....

一个超长的数字.

推荐答案

Visual Studio 通常不允许您分配大于 0x7fffffff 字节的数组并出现错误:

Visual studio doesn't normally allow you to allocate arrays larger than 0x7fffffff bytes with the error:

error C2148: total size of array must not exceed 0x7fffffff bytes

在这种情况下,我猜有一个编译器错误会阻止检测超大数组,并且数组未正确初始化.

I guess there is a compiler bug that prevents the detection of the oversize array in this case and the array is not initialised correctly.

使用 std::vector 代替并在堆上分配数组有效:

Using std::vector instead and allocating the array on the heap works:

#include <stdio.h>
#include <vector>

constexpr auto array_size = 50000000;

int main()
{
    std::vector < std::vector< std::vector< double > > > M( array_size, std::vector< std::vector< double > >( 2, std::vector< double >( 20 ) ) );
    for (int n = 0; n < array_size; n++)
        printf("%d %f\n", n, M[n][0][0]);
}

请注意,这将使用超过最低要求的 16GB 内存,如果您确实需要一次将所有数据保存在内存中,单维向量可能会更有效.

Note that this will however use more than the minimum required 16GB of memory, if you really need to have all the data in memory at once a single dimensional vector may be more efficient.

这篇关于巨大数组中的访问冲突?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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