所以我正在使用Jetbrains Clion IDE在C ++中编写光线跟踪器。当我尝试创建启用了多重采样抗锯齿的600 * 600图像时,我的内存不足。我收到这个错误:
在抛出'std :: bad_alloc'实例后终止调用 what():std :: bad_alloc
此应用程序已请求运行时将其终止 不寻常的方式请联系应用程序的支持团队获取更多信息 信息。
我的渲染功能代码:
宽度:600 身高:600 numberOfSamples:80
void Camera::render(const int width, const int height){
int resolution = width * height;
double scale = tan(Algebra::deg2rad(fov * 0.5)); //deg to rad
ColorRGB *pixels = new ColorRGB[resolution];
long loopCounter = 0;
Vector3D camRayOrigin = getCameraPosition();
for (int i = 0; i < width; ++i) {
for (int j = 0; j < height; ++j) {
double zCamDir = (height/2) / scale;
ColorRGB finalColor = ColorRGB(0,0,0,0);
int tempCount = 0;
for (int k = 0 ; k < numberOfSamples; k++) {
tempCount++;
//If it is single sampled, then we want to cast ray in the middle of the pixel, otherwise we offset the ray by a random value between 0-1
double randomNumber = Algebra::getRandomBetweenZeroAndOne();
double xCamDir = (i - (width / 2)) + (numberOfSamples == 1 ? 0.5 : randomNumber);
double yCamDir = ((height / 2) - j) + (numberOfSamples == 1 ? 0.5 : randomNumber);
Vector3D camRayDirection = convertCameraToWorldCoordinates(Vector3D(xCamDir, yCamDir, zCamDir)).unitVector();
Ray r(camRayOrigin, camRayDirection);
finalColor = finalColor + getColorFromRay(r);
}
pixels[loopCounter] = finalColor / numberOfSamples;
loopCounter++;
}
}
CreateImage::createRasterImage(height, width, "RenderedImage.bmp", pixels);
delete pixels; //Release memory
}
我是C ++的初学者,所以我非常感谢你的帮助。我也尝试在Microsoft Visual Studio中使用C#做同样的事情,内存使用率从未超过200MB。我觉得我犯了一些错误。如果您想帮助我,我可以为您提供更多详细信息。
答案 0 :(得分:2)
使用new []
分配的内存必须使用delete []
解除分配。
由于使用
,您的程序有未定义的行为delete pixels; //Release memory
释放内存。它必须是:
delete [] pixels;