2014-03-04 48 views
0

想知道我的刪除操作有什麼問題。是,我必須用我的教授聲明的變量刪除數組LN

LN** map = nullptr; 

對我工作的分配,使用簡單的數據類型是不是一種選擇。

class LN { 
public: 
    LN()      : next(nullptr) {} 
    LN (const LN& ln)   : value(ln.value), next(ln.next) {} 
    LN (int v, LN* n = nullptr) : value(v), next(n) {} 

    int value; 
    LN* next; 
}; 

int main() 
{ 
    LN** array = nullptr; 
    array = new LN*[5]; 
    int j=1; 
    for (int i=0; i<5; ++i) { 
     array[i] = new LN(); 
     array[i] = new LN(j++, array[i]); 
     array[i] = new LN(j++, array[i]); 
    } 

// What I think should work, but doesn't. 

    for (int i=0; i<5; ++i) { 
     delete array[i]; 
    } 

    delete[] array; 
    array = nullptr; 

    return 0; 
} 
+0

加入析構函數在這種情況下,有一個非常明顯的錯誤,但你應該解釋*如何*究竟它不工作(你有什麼期望發生與實際發生的情況)。 – jerry

回答

1

沒有什麼錯在這裏你刪除嘗試。它將成功刪除當前存儲在數組中的所有元素,然後是數組本身。

問題是LN的析構函數沒有正確清理列表中的所有值。當頭LN值被刪除時,這導致所有next指針泄漏。在這裏嘗試

~LN() { 
    delete next; 
} 
+0

不同意。 'LN'不分配任何內存,所以它不應該清理它。 – jerry