2013-06-28 92 views
0

在我目前正在使用的程序中,我有包含std::vectors的對象。當我嘗試刪除這些對象時,出現問題,沒有內存從對象中釋放。如何釋放一個包含std :: vector的對象的內存

我做了一個最小程序來測試這個,並且不能使它在這個程序中正常工作。

這是我用來測試的程序。

#include<iostream> 
#include<vector> 

struct node{ 

    std::vector<int> list; 

    bool isParent; 
    struct node* child; 

    ~node(){ 
     delete[] child; 
    } 

    node(){ 
     isParent = false; 
     list.push_back(5); // comenting this line would make it work correctly 
    } 

    void divide_r(){ 
     if (isParent){ 
      for(int i = 0; i < 8; i++){ 
       (child+i)->divide_r(); 
      } 
     }else{ 
      node *c; 
      c = new node[8]; 
      child = &c[0]; 
      isParent = true; 
     } 
    } 
}; 

int main(){ 


    node *root = new node; 

    for(int i = 0; i < 8; i++){ 
     root->divide_r(); 
    } 

    delete root; 

    sleep(10); 

    return 0; 
} 

所以,如果我推入任何東西到矢量中,我不能釋放任何內存。

我使用的是g ++如果有問題的話。我做錯了什麼,或者應該這樣做嗎?我也嘗試過使用不同的方法從析構函數中的「list」中釋放內存,但是因爲「list」將會超出範圍,所以我應該將其釋放。

該程序將使用大約1.4GB的RAM,但在睡眠和程序退出之前沒有任何東西被釋放。

+3

你爲什麼要使用向量的'list'成員*而不是爲'child'成員*? –

+5

這是通常的東西 - 釋放的內存不會立即返回到操作系統,而是由分配器保存,所以正常情況下,您看不到內存使用情況立即減少。 –

+1

設置不要緊,因爲它只是一個測試。如果我比Matteo正確理解,內存應該在需要時被釋放?所以如果我試圖在刪除後再次填充內存,它將根據需要返回? – lasvig

回答

2

嘗試分配您的對象,然後刪除它們。 分配新對象時,您會注意到,該操作系統不會顯示增加的內存使用情況。

你也可以通過valgrind運行你的示例,你應該注意到,它不會抱怨內存泄漏。

原因很明顯。 C庫希望避免調用OS來分配和返回每一小塊內存的額外開銷。

相關主題:Linux Allocator Does Not Release Small Chunks of MemoryDoes calling free or delete ever release memory back to the "system"

相關問題