c++ - 为什么我会用完堆内存?

标签 c++ memory overflow raytracing msaa

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

terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc

This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information.

我的渲染函数代码:

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

最佳答案

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

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

delete pixels;      //Release memory

释放内存。它必须是:

delete [] pixels;

关于c++ - 为什么我会用完堆内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36525941/

相关文章:

css - 当网格元素与末尾/底部对齐时滚动不起作用

html - 特定文本字符可以更改行高吗?

javascript - javascript 对象的合理大小是多少

python - 优化大量数据的搜索和插入操作

c++ - 无法使用 GDB 进入共享库中的函数

c++ - DVD 或 CD 播放器?

Java内存模型: compiler rearranging code lines

CSS 问题 - 水平滚动条隐藏了内容

c++和MySQL的连接

c++ - MATLAB MEX 文件构建成功但未显示任何内容