2013-06-04 131 views
2

我想創建一個向量,每個結構都有一個指針數組。但是,我似乎無法刪除沒有內存問題的向量。結構與指針的C++向量

當運行的valgrind

== 29801 ==無效免費()/刪除/刪除[]/realloc()的 == 29801 ==在0x4A05A36:操作者刪除(vg_replace_malloc.c:515 ) == 29801 == by 0x4009D4:test_struct ::〜test_struct()(in /home/hltcoe/rcotterell/code-switching/a.out) == 29801 == by 0x40142B:void std :: _ Destroy(test_struct *)(在 /home/hltcoe/rcotterell/code-switching/a.out) == 29801 == by 0x401299:void std :: _ Destroy_aux :: __ destroy(test_struct *, test_struct *)(in/home/hltcoe/rcotterell/code-switching/a.out)

編輯

#include <vector> 
using namespace std; 

struct test_struct { 
    public: 
    int * array; 
    test_struct() { 
     array = NULL; 
    } 
    ~test_struct() { 
     delete[] array; 
    } 
    private: 
    test_struct(const test_struct& that); 
    test_struct& operator=(const test_struct& that); 
}; 

int main(int argc, char ** argv) { 

    vector <test_struct> data; 

    for (int i = 0; i < 5; ++i) { 
     test_struct tmp; 
     tmp.array = new int[5]; 
     data.push_back(tmp); 
    } 
} 

而且它提供了以下編譯錯誤。有任何想法嗎?

+0

可能重複[三條法則是什麼?](http://stackoverflow.com/questions/4172722/what-is-the-rule-of-ree) – juanchopanza

回答

2

由於test_struct析構函數以及您試圖將結構存儲在vector中的事實,因此您的解決方案不起作用。
test_struct tmp被推送到該向量時,將創建一個test_struct的副本。然後tmp與致電delete[] array一起銷燬,vector <test_struct> data中的副本最終以懸掛指針結束。
你可能需要重新考慮你的架構,或至少增加了test_struct一個拷貝構造函數,將整個陣列複製

3

您應該遵循rule of three或使用STL容器,其中以往任何時候都可能:

struct test_struct 
{ 
    explicit test_struct(int size) : array(size) { }  
    std::vector<int> array; 
}; 


int main() 
{ 
    vector <test_struct> data(5, test_struct(5)); 

    return 0; 
}