c++中动态2d字符串数组的解除分配

deallocation of a dynamic 2d string array in c++

本文关键字:数组 解除分配 字符串 2d 动态 c++      更新时间:2023-10-16

我很难理解为什么我的删除方法不正确。

对于我的矩阵创建,我有:

 43    matrix = new string*[row];
 44    for(int i = 0; i < row; i++) {
 45       matrix[i] = new string[col];
 46    }
 47    for(int i = 0; i < row; i++) {
 48       for(int j = 0; j < col; j++) {
 49          matrix[i][j] = array[i][j];
 50          //cout << matrix[i][j] << ' ';
 51       }
 52       cout << endl;
 53    }

然后在我的析构函数中我有:

 15    for(int i = 0; i < row; i++) {
 16       delete matrix[i];
 17    }
 18    delete matrix;

我的程序在删除的第一个条目时崩溃

如前所述,必须将new[]delete[]配对。在这些行中:

matrix = new string*[row];
matrix[i] = new string[col];

您使用new[],因此稍后,您必须执行:

delete[] matrix[i];
delete[] matrix;

如需参考,请参阅此链接。

当你分配你的二维数组时,你真的创建了N一维数组。现在每一个都必须删除,但系统不知道它们有多少。顶级数组,即指向第二级的指针数组arrays,就像C中的任何其他数组一样:它的大小不是由系统。

如果您使用delete而不是delete []:,以下是valgrind要说的话

==30045== Mismatched free() / delete / delete []
==30045==    at 0x4A05FD6: operator delete(void*) (vg_replace_malloc.c:480)
==30045==    by 0x400725: main
==30045==  Address 0x4c2e040 is 0 bytes inside a block of size 160 alloc'd
==30045==    at 0x4A07152: operator new[](unsigned long) (vg_replace_malloc.c:363)
==30045==    by 0x400715: main
 matrix = new string*[row];
 for(int i = 0; i < row; i++) {
    matrix[i] =delete[col];
 }
delete[] matrix;