在使用vs2010编译(并执行)这个c ++代码时,我甚至在它甚至可以向控制台一瞥“Start”之前就得到了堆栈溢出异常。
我使用的所有头文件都包含在stdafx.h中,但这显然不是问题(直接包含头文件时同样的问题)。
堆栈跟踪如下:
> msvcr100d.dll!__set_flsgetvalue() Zeile 145 + 0xc Bytes C
msvcr100d.dll!_getptd_noexit() Zeile 500 C
msvcr100d.dll!_getptd() Zeile 523 + 0x5 Bytes C
msvcr100d.dll!_LocaleUpdate::_LocaleUpdate(localeinfo_struct * plocinfo) Zeile 243 + 0x5 Bytes C++
003efe3c()
TerrainGenerator.exe!pre_cpp_init() Zeile 298 + 0x21 Bytes C
任何帮助都会非常感激,我是c ++的绝对初学者,正如你在代码风格中看到的那样,我尝试了一切以摆脱这个烦人的问题,例如甚至没有声明一个额外的功能和等等...请帮助我,不要犹豫,询问您是否需要其他信息。 提前谢谢。
#include "stdafx.h"
int main(int argc, char* argv[])
{
puts("Start");
const int res = 4096;
srand(time(NULL));
uint16_t data[(res+1)*(res+1)];
uint16_t variance = 2000;
int seed = 1337;
data[0] = ((seed>>1)+(int)(rand()/(RAND_MAX*(seed+(seed>>1)))));
data[res] = ((seed>>1)+(int)(rand()/(RAND_MAX*(seed+(seed>>1)))));
data[res*res] = ((seed>>1)+(int)(rand()/(RAND_MAX*(seed+(seed>>1)))));
data[res*(res+1)] = ((seed>>1)+(int)(rand()/(RAND_MAX*(seed+(seed>>1)))));
int count = 0;
for(int size=res;size>=1;size=size>>1,variance=variance>>1)
{
count++;
for(int x=size;x<res;x+=size<<1)
{
for(int y=size;y<res;y+=size<<1)
{
data[x*res+y] = data[(x-size)*res+(y-size)] + data[(x-size)*res+(y+size)] + data[(x+size)*res+(y-size)] + data[(x+size)*res+(y+size)];
data[x*res+y] /= 4;
data[x*res+y] += (variance>data[x*res+y])?(-(data[x*res+y]^2/variance)+(int)(rand()/(RAND_MAX*(data[x*res+y]^2/variance)))):(-variance+(int)(rand()/(RAND_MAX*variance*2)));
}
}
for(int x=0;x<res;x+=size)
{
for(int y=0;y<res;y+=size)
{
if(x!=res-1)
{
data[(x+(size>>1))*res+y] = data[x*res+y] + data[(x+size)*res+y] + ((y!=res-1)?data[(x+(size>>1))*res+(y+(size>>1))]:0) + ((y!=0)?data[(x+(size>>1))*res+(y-(size>>1))]:0);
data[(x+(size>>1))*res+y] /= (y!=res-1&&y!=0)?4:3;
data[(x+(size>>1))*res+y] += (variance>data[(x+(size>>1))*res+y])?((-(data[(x+(size>>1))*res+y]^2/variance)+(int)(rand()/(RAND_MAX*(data[(x+(size>>1))*res+y]^2/variance))))):(-variance+(int)(rand()/(RAND_MAX*variance*2)));
}
if(y!=res-1)
{
data[x*res+(y+(size>>1))] = data[x*res+y] + data[x*res+(y+size)] + ((x!=res-1)?data[(x+(size>>1))*res+(y+(size>>1))]:0) + ((x!=0)?data[(x-(size>>1))*res+(y+(size>>1))]:0);
data[x*res+(y+(size>>1))] /= (x!=res-1&&x!=0)?4:3;
data[x*res+(y+(size>>1))] += (variance>data[x*res+(y+(size>>1))])?((-(data[x*res+(y+(size>>1))]^2/variance)+(int)(rand()/(RAND_MAX*(data[x*res+(y+(size>>1))]^2/variance))))):(-variance+(int)(rand()/(RAND_MAX*variance*2)));
}
}
}
}
size_t Count = res*res;
uint16_t* Block = data;
char* Path = "export.raw";
if(!Block) return false;
FILE * filePointer = NULL;
errno_t error = fopen_s(&filePointer, Path, "wb");
if(error) return false;
fwrite(Block, sizeof(uint16_t), Count, filePointer);
fclose(filePointer);
return true;
return 0;
}
答案 0 :(得分:10)
问题是
uint16_t data[(res+1)*(res+1)];
它是一个16 MB +的本地数组,太大而不适合堆栈(通常为1 MB) - 你必须使用new
语句在堆中创建它:
uint16_t* data = new uint16_t[(res+1)*(res+1)];
然后记得在你不再需要时用delete
语句取消分配它:
delete[] data;