2013-04-28 63 views
0

我用指針來創建一個數組,然後在析構函數Valgrind的抱怨內存泄漏,但我打電話new和delete

class cBuffer{ 
    private: 
    struct entry { 
     uint64_t key; 
     uint64_t pc; 
    }; 
    entry *en; 
    public: 
    cBuffer(int a, int b, int mode) 
    { 
     limit = a; 
     dist = b; 
     md = mode; 
     en = new entry[ limit ]; 
     for (int i=0; i<limit; i++) { 
     en[i].key = 0; 
     en[i].pc = 0; 
     } 
    }; 
    ~cBuffer() { delete [] en; } 
    ... 
    } 

在另一大類我用cBuffer這樣寫道刪除過程:

class foo() { 
    cBuffer *buf; 
    foo() 
    { 
    buf = new cBuffer(gSize, oDist, Mode); 
    } 
}; 

然而,Valgrind的抱怨新的運營商

==20381== 16,906,240 bytes in 32 blocks are possibly lost in loss record 11,217 of 11,221 
==20381== at 0x4A0674C: operator new[](unsigned long) (vg_replace_malloc.c:305) 
==20381== by 0x166D92F8: cBuffer::cBuffer(int, int, int) 
+4

您沒有遵循三個規則。 – 2013-04-28 14:37:26

+0

見:https://en.wikipedia.org/wiki/Rule_of_three_(C%2B%2B_programming) – 2013-04-28 14:40:43

+0

@mahmood:見[這裏](http://stackoverflow.com/questions/4172722);如果你管理資源,並在析構函數釋放它,那麼你幾乎肯定需要落實或刪除拷貝構造函數和拷貝賦值運算符,否則,你可以用兩個對象最終都試圖釋放相同的資源。 – 2013-04-28 14:41:17

回答

2
cBuffer *buf; 
    foo() 
    { 
    buf = new cBuffer(gSize, oDist, Mode); 
    } 

你需要調用

delete buf; 

既然你明確要求new

0

class foo會導致你的泄漏,因爲你永遠不會刪除動態分配的cBuffer。解決方案很簡單:在這裏完全不需要動態分配。

class foo { 
    cBuffer buf; // An object, not a pointer 
    foo() : buf(gSize, oDist, Mode) {} 
}; 

更一般地,當你需要動態分配,要小心,你總是deletenew。最可靠的方法是使用容器和智能指針等RAII類型爲您管理所有動態資源。

+0

爲什麼我用指針的原因是這裏討論http://stackoverflow.com/questions/15922760/creating-an-object-in-the-constructor-or-an-init-function – mahmood 2013-04-28 14:53:40

+0

@mahmood:我沒有看到指針的任何討論那裏,只是一些不好的建議告訴你使用指針,當你不需要,還有一些更好的建議,告訴你不要。 – 2013-04-28 14:54:47