0

所以我正在使用 Jetbrains Clion IDE 用 C++ 编写光线追踪器。当我尝试创建启用了多重采样抗锯齿的 600 * 600 图像时,内存不足。我收到此错误:

在抛出 'std::bad_alloc'
what() 的实例后调用终止:std::bad_alloc

此应用程序已请求运行时以不寻常的方式终止它。请联系应用程序的支持团队以获取更多信息。

我的渲染函数代码:

宽度:600 高度:600 样本数: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。我觉得我做错了什么。如果您想帮助我,我可以为您提供更多详细信息。

4

1 回答 1

2

使用分配的内存new []必须使用 释放delete []

您的程序由于使用了未定义的行为

delete pixels;      //Release memory

释放内存。它需要是:

delete [] pixels;
于 2016-04-10T04:58:05.707 回答