2013-07-13 19 views
0

好吧,我簡化我的代碼到最低限度,以便它不是一個很長的列表發佈..問題是代碼崩潰時,我完成程序,即析構函數被調用。因爲point類是在ptlist類中的,並且board類中的ptlist我認爲我必須如何鏈接,然後在析構函數中刪除對象時它會崩潰,但在到達if(item!= NULL)行後崩潰ptlist的析構函數...它不會因爲某些原因不輸入if子句和else子句..不知道爲什麼..反正繼承了我的程序的細化代碼:如何在C++中以深度順序破壞幾個類

[編輯]我感謝你們所有人修復了代碼,現在它完美運行。謝謝大家

#include <windows.h> //include all the basics 
#include <tchar.h> //string and other mapping macros 
#include <string> 
#include <ctime> 
#include <stdlib.h> 
#include <algorithm> 
#include <iostream> 
using namespace std; 

class point 
{ 
    unsigned x; 
    unsigned y; 
    int id; 
    int type; 
    bool covered; 
    int maze; 

public: 
    point(){x = 0; y = 0; id = 0; type = -1; covered = true; maze = 0;} 
    ~point(){x = 0; y = 0; id = 0; type = 0; covered = true; maze = 0;} 
}; 

class ptlist 
{ 
    point ** item; 
    int length; 
    int itemmax; 

public: 
    ptlist(){item = NULL; length = 0; itemmax = 0;} 
    ptlist(int imax); 
    ~ptlist(); 
}; 

ptlist::ptlist(int imax) 
{ 
    item = new point *[imax]; 
    length = 0; 
    itemmax = imax; 
} 

ptlist::~ptlist() 
{ 
    delete [] item; 
} 

class board 
{ 
    ptlist *wall; 
    ptlist *path; 

public: 
    board(){wall = new ptlist(1); path = new ptlist(1);} 
    ~board(){delete wall; delete path;} 
}; 
+3

這是* not * C. – 2013-07-13 06:13:22

+0

在你的'point'tor處有一些複製和浪費錯誤。 – dyp

+1

這段代碼如何編譯?我的意思是'〜board()刪除[]牆;刪除[]路徑;}'是不正確的語法,你錯過了大括號。在課堂結束時,你還有一個隨機的'* this;'。另外,規則是如果你'刪除'你刪除[]'''''''''所以你應該修復你的析構函數。 – Borgleader

回答

0

你的邏輯在~ptlist()顯然是錯誤的。當您知道itemNULL時,您打電話給delete item。您應該刪除else子句。

此外,您的構造函數ptlist(int max)從不爲每個指針創建一個點數組。

+4

'delete NULL'是明確的......(雖然在這種情況下顯然是無稽之談) –

+0

啊,我不知道。感謝您指出了這一點。但是,整個條款仍然是完全多餘的。 – cheeyos

0

你正在使用delete[],你不應該。

wall = new ptlist(1); 
delete wall; // NOT delete [] wall 

path相同。

規則是當你分配一個數組(使用new [])你釋放與delete[]。當您使用new進行分配時,您可以使用delete取消分配。

此外,您正在創建一個指向數組的指針或陣列指向數組的指針數組。無論如何,你永遠不會初始化這些指針,但它們後面會有delete。 你應該將它們至少初始化爲NULL在構造函數:

ptlist::ptlist(int imax) 
{ 
    item = new point *[imax]; 
    for(int i = 0; i<imax; ++i) 
     item[i] = NULL; 
    length = 0; 
    itemmax = imax; 
} 

,如果他們數組和不是單個點,你應該在析構函數delete []刪除它們。

0

除了令人困惑的刪除和刪除[]外,您不需要循環刪除由new []分配的數組的所有元素。運算符delete []爲你做。見#5.3.5(6)。你正在做重複釋放,這會導致未定義的行爲。