简体   繁体   English

在C ++中动态2D字符串数组的重新分配

[英]deallocation of a dynamic 2d string array in c++

I'm having trouble understanding why my delete method is incorrect. 我无法理解为什么我的删除方法不正确。

For my matrix creation I have: 对于我的矩阵创建,我有:

 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    }

Then in my destructor I have: 然后在我的析构函数中:

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

My program crashes on the first entry of deletion 我的程序在删除的第一个条目时崩溃

As already stated, you must pair new[] with delete[] . 如前所述,您必须将new[]delete[]配对。 In these lines: 在这些行中:

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

You use new[] , therefore later on, you must do: 您使用new[] ,因此稍后,您必须执行以下操作:

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

For reference, see this link . 供参考,请参阅此链接

When you allocated your two-dimensional array, you really created N one-dimensional arrays. 分配二维数组时,实际上创建了N个一维数组。 Now each of those have to be deleted, but the system does not know how many of them there are. 现在必须删除其中的每一个,但是系统不知道其中有多少个。 The size of the top-level array, ie the array of pointers to your second-level arrays, is just like any other array in C: its size is not stored by the system. 顶级数组的大小(即,指向第二级数组的指针的数组)与C中的任何其他数组一样:系统不存储其大小。

Here's what valgrind has to say if you use delete instead of delete [] : 如果您使用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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM