c++ - 为什么在为数组分配新值时会崩溃?

标签 c++ arrays visual-c++ for-loop set

<分区>

Possible Duplicate:
Could not allocate memory

我的以下代码运行良好:

double weight [600] [800][3];
double mean [600] [800][3];
double sd [600] [800][3];
double u_diff [600] [800][3];

for ( int i = 0; i < 600; i ++ )
{
    for ( int j = 0; j < 800; j ++ )
    {
        for ( int k=0; k < 3; m ++ )
        {
            weight [i][j][k] = 0;
            mean[i][j][k] = 0; 
            sd[i][j][k] = 6;        
        }       
    }
}

但是当我把它改成这种形式时:

int init = 6;
int C = 3;

for ( int i = 0; i < 600; i ++ )
{
    for ( int j = 0; j < 800; j ++ )
    {
        for ( int k =0; k < 3; k ++ )
        {
            weight [i][j][k] = 1/C;
            mean[i][j][k] = rand(); 
            sd[i][j][k] = init;         
        }       
    }
}

它崩溃了。我什至尝试分别为“重量”、“平均值”和“标准差”工作。我怀疑它可能是数据类型,更改为:

double value = rand();
weight[i][j][m] = value;

但错误仍然存​​在。这里有什么问题?

最佳答案

我也遇到了第一个崩溃的版本(cygwin,4.5.3)。

问题与有限的堆栈大小有关,大约为 2 MB。

为什么不会崩溃可能是因为优化:
由于另一个片段中的“rand”,优化器/编译器不可能
告诉数组根本没有被使用——这很可能是可见的
来自第一个片段。

gcc -std=c99 tst.c -O  && ./a.exe -- produces nothing
gcc -std=c99 tst.c && ./a.exe -- segmentation fault

要解决这个错误,只需使用 malloc 从堆中分配大数组 (或者通过使用相当小的 80x60x3 阵列来研究极限?)

// tst.c
// compile and run with gcc -std=c99 tst.c -DOK=0 -DW=80 -DH=60 && ./a.exe    // ok
//               or     gcc -std=c99 tst.c -DOK=0 -DW=800 -DH=600 && ./a.exe  // crash
//               or     gcc -std=c99 tst.c -DOK=1 -DW=800 -DH=600 && ./a.exe  // ok
#include <stdlib.h>
int main()
{
#if OK
    double *weight =(double*)malloc(W*H*3*sizeof(double));      // no crash
#else
    double weight[W*H*3];   // crash when W*H is large, nocrash when W*H is small
#endif
    int z=0;
    for ( int i = 0; i < W; i ++ )
    {
        for ( int j = 0; j < H; j ++ )
        {
            for ( int m =0; m < 3; m ++ )
            {
                 weight[z++]=0;     
            }       
        }
    }
    return 0;
}

关于c++ - 为什么在为数组分配新值时会崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12746768/

相关文章:

c++ - 如何更改 drawText 上的字体大小?

c++ - Linux 上的异​​步套接字发送

c++ - 提升 ASIO : How can a server know if a client is still connected?

C语言编程棋盘游戏

arrays - 如何只允许一定长度的数组参数

ruby-on-rails - 在 Rails 3.2 中从数组调用 ActiveRecord 关联方法

c++、msxml 和智能指针

c++ - 源文件中成员函数模板的显式特化

opencv - 有没有办法从OpenCV中的Hough变换中提取单行?

c++ - Http post - 发送大数据时连接重置 vc++