簡體   English   中英

“ std :: bad_alloc”:我使用的內存過多嗎?

[英]“std::bad_alloc”: am I using too much memory?

消息:

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

我查看了gdb backtrace,這是我自己實現的最低級別的方法:

/*
 * get an array of vec3s, which will be used for rendering the image
 */
vec3 *MarchingCubes::getVertexNormalArray(){
    // Used the same array size technique as getVertexArray: we want indices to match     up
    vec3 *array = new vec3[this->meshPoints.getNumFaces() * 3]; //3 vertices per face

    int j=0;
    for (unsigned int i=0; i < (this->meshPoints.getNumFaces() * 3); i++) {
        realVec normal = this->meshPoints.getNormalForVertex(i);
 //     PCReal* iter = normal.begin();

        if (normal.size() >= 3) {
            array[j++] = vec3(normal[0], normal[1], normal[2]);
        }
        cout << i << " ";
    }

    return array;
}

您在上面看到的cout語句表明它在7000次以上迭代后終止。 在我的應用程序接近結束時,上述函數僅被調用一次。 在調用上面的函數之前,我調用了一個非常類似的函數,這不會引起問題。

(從注釋中移動/擴展)

由於您每次都在分配新數組而不分配它,因此會發生大量內存泄漏,即,您繼續向系統請求內存而從未將其退還給系統。 最終,堆上的空間完成了,在下一次分配時,您得到的只是一個std::bad_alloc異常。

“ C風格”的解決方案是記住當您不再需要此類內存時(使用delete[] )來釋放該內存,但這是(1)容易出錯的(例如,如果您內部有多個返回路徑,函數)和(2)潛在的異常不安全(如果有異常,每條指令都會成為潛在的返回路徑!)。 因此,應避免這種方式。

慣用的C ++解決方案是使用智能指針 -封裝指針並在銷毀它們時銷毀相關內存的小對象-或標准容器,它們或多或少地具有相同的功能,但是具有復制語義和更多的花哨功能(包括將數組的大小存儲在其中)。

我在嘗試分配負長度數組時遇到此錯誤:

double myArray =新的double [-9000];

以防萬一,它可以幫助任何人。

我的問題原來是this->meshPoints.getNormalForVertex(i)訪問長度小於this->meshPoints.getNumFaces() * 3的數組(或矢量,我不記得了)。 因此它進入了邊界。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM