2015-04-05 101 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维阵列。