2016-04-10 157 views
0

所以我正在使用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米 的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

您是否在使用昂貴的功能?這可能是除了不釋放內存之外的原因。 – Auriga

回答

2

使用new []分配的內存必須使用delete []重新分配。

程序具有不確定的行爲,由於使用的

delete pixels;  //Release memory 

釋放內存。它需要是:

delete [] pixels; 
+0

對不起,它沒有任何效果。 –

+0

@sashankAryal,我看不到任何突出的問題。如果你能想出一個[最小化,完整和可驗證的例子](http://stackoverflow.com/help/mcve)會很有幫助。 –