2015-04-05 84 views
0

我在我的代碼中使用了二維動態分配數組。一切正常,直到我的程序試圖調用我的tablica2D對象的析構函數。當我的程序到達最後的delete[] tab命令時,我收到一個運行時錯誤「HEAP CORRUPTION DETECTED」。這是否意味着它之前的循環已經釋放了分配給tab的所有內存?我的印象是,要釋放所有動態分配的內存,每個new命令需要有一個delete命令。或者是其他的東西導致這個錯誤?C++刪除二維動態分配數組

這是這是造成我的麻煩之類的代碼:

class tablica2D 
{ 
    static const int k = 2; 
    int n, m; 
    string **tab; 
public: 
    tablica2D(int n, int m) 
    { 
     this->n = n; 
     this->m = m; 

     tab = new string*[n]; 
     for (int i = 0; i < m; i++) 
     { 
      tab[i] = new string[m]; 
     } 
    } 
    string* operator [](int n) 
    { 
     return tab[n]; 
    } 
    static const bool compareRows(const string* i, const string* j) 
    { 
     int x = atoi(i[k].c_str()); 
     int y = atoi(j[k].c_str()); 
     return x > y; 
    } 
    void sort() 
    { 
     std::sort(tab, tab + n, compareRows); 
    } 
    ~tablica2D() 
    { 
     for (int i = 0; i < n; i++) 
     { 
      delete[] tab[i]; 
     } 
     delete[] tab; 
    } 
}; 
+1

是否有你不使用['std :: vector'](http://en.cppreference.com/w/cpp/container/vector)的原因? – 2015-04-05 16:07:05

+1

爲什麼對天堂' s爲什麼你自己努力與內存管理,它是完全可用的[標準c + +容器](http://en.cppreference.com/w/cpp/container)和[動態內存管理](http://en.cppreference.com/w/cpp/memory)? – 2015-04-05 16:09:55

+0

@πάνταῥεῖ也許這是一個任務。 – 2015-04-05 16:11:09

回答

2

您使用了錯誤的變量在new循環,另外創建一個三維數組,而不是一個二維數組:

for (int i = 0; i < m; i++) 
    //     ^^, should be n 
    { 
     tab[i] = new string[m]; 
     //     ^^^ 
     // should be new string, not new string[m] 
    } 

VS:

for (int i = 0; i < n; i++) 
    //     ^^, this one is correct 
    { 
     delete[] tab[i]; 
    } 
+0

它不應該是'n'而不是'm'嗎? – user7 2015-04-05 16:13:47

+0

實際上它也應該是在第一個循環中,但在這個變化之後一切正常。我錯過了這個,因爲我在測試中使用了m> n,所以我的數組有多餘的空行,但可以適合我試圖放入的所有內容。感謝您的快速響應。 – Kurigalzu 2015-04-05 16:14:37

+0

@Kurigalzu即使發生這種變化,你的'tablica2D'類也很容易被兩行main()程序破壞。 '{tablica2D t1(10,10); tablica2D t2 = t1; }'你沒有在你的課堂上實施「3的規則」。 – PaulMcKenzie 2015-04-05 16:21:07

0

如果我需要一個類C的2D陣列我總是使用:

type **myarr = new type*[X]; 
myarr[0] = new type[X*Y]; 
for (int i = 1; i < X; i++) { 
    myarr[i] = myarr[0] + i * Y; 
} 

有關用法:

myarr[x][y] 

然後用於釋放:

delete[] myarr[0]; 
delete[] myarr; 

同樣,有一些小的努力,可以應用用於N維陣列。