c++中动态2d字符串数组的解除分配
deallocation of a dynamic 2d string array in c++
我很难理解为什么我的删除方法不正确。
对于我的矩阵创建,我有:
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;
相关文章:
- 字符指针数组内存分配
- 当按下 SFML C++时,如何在数组中分配值
- C++编译时使用 constexpr 字符数组指针分配静态数组?
- 将数组动态分配到具有指针参数的函数中
- C++ 无法将字符数组变量分配给字符串变量
- 数组大小分配错误
- C++如何在函数中传递字符串数组并分配给变量?
- 使用 new: "potentially uninitialized pointer"将对象数组动态分配给指针
- 无法在重载运算符时将数组元素分配给类变量"="
- 2D 数组内存分配 (malloc) 返回 NULL
- C 数组值分配时间
- 为什么C 没有方便的方式来为多维数组动态分配内存
- 如何根据输入在数组中分配多个索引
- 通过参考数组传递分配的堆栈参数
- 将数组匹配分配给字符串
- 动态数组仅分配一个元素
- C 中的多维数组的分配,部分为可变长度
- 多维数组动态分配的内存图
- 你怎么知道如何解除指针数组的分配
- 使用delete[]为一维常量的2d数组解除内存分配