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;
}
}
}
它崩溃了。我什至尝试分别为“ weight”,“ mean”和“ sd”工作。我怀疑它可能是数据类型,更改为:
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/