我已经盯着这个有一段时间了,我不明白为什么它会失败。我有一个 CMatrix 类,实现一个二维矩阵,如下所示:
class CMatrix {
public:
CMatrix(int height, int width);
~CMatrix();
// more stuff here
private:
void deleteData();
void allocData(int height, int width);
int rows, cols;
double** data;
};
CMatrix::CMatrix(int height, int width) {
allocData(height, width);
}
CMatrix::~CMatrix() {
deleteData();
}
它工作正常,直到我试图摧毁它。有两种方法负责分配和释放,定义如下:
void CMatrix::allocData(int height, int width) {
this->rows = height;
this->cols = width;
data = new double*[rows];
for (int i = 0; i < rows; i++) {
data[i] = new double[cols];
for (int j = 0; j < cols; j++)
data[i][j] = 0;
}
}
void CMatrix::deleteData() {
for (int i = 0; i < rows; i++) {
delete data[i];
}
delete [] data;
}
这个简单的main
代码会导致它发生故障:
int main(int argc, char**
CMatrix a(2, 3);
a[0][0] = 1;
a[0][1] = 2;
a[0][2] = 3;
a[1][0] = 4;
a[1][1] = 5;
a[1][2] = 6;
return 0;
}
valgrind 说:
==21005== Mismatched free() / delete / delete []
==21005== at 0x4C2A44B: operator delete(void*) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==21005== by 0x402B5C: CMatrix::deleteData() (main.cpp:375)
==21005== by 0x401731: CMatrix::~CMatrix() (main.cpp:138)
==21005== by 0x402F5D: main (main.cpp:598)
==21005== Address 0x5a06090 is 0 bytes inside a block of size 24 alloc'd
==21005== at 0x4C2AAA4: operator new[](unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==21005== by 0x402A84: CMatrix::allocData(int, int) (main.cpp:366)
==21005== by 0x4015FB: CMatrix::CMatrix(int, int) (main.cpp:123)
==21005== by 0x402D63: main (main.cpp:415)
在方法deleteData()
和中打印此消息i=0
。i
对于其他s 和 delete[],它什么也没说。
我究竟做错了什么?