【发布时间】:2017-05-25 01:27:31
【问题描述】:
我的问题是为什么析构函数不释放临时数组的内存? Valgrind 告诉我,我在构造函数中使用了 new 运算符,但之后没有删除内存。当我简单地写delete temp 时,我在 Valgrind 中遇到了许多错误,例如 Invalid read of size、double free 等。你们能告诉我这里发生了什么吗?
array_xyz(const int r, const int c, double **arg_array) {
rows = r;
cols = c;
array_xyz *temp = new array_xyz();
temp->arr = new double *[rows];
temp->rows = r;
temp->cols = c;
arr = new double *[rows];
for (int i = 0; i < rows; i++) {
arr[i] = new double [cols];
temp->arr[i] = new double [cols];
}
for (int j = 0; j < rows; j++) {
for (int k = 0; k < cols; k++)
temp->arr[j][k] = arg_array[j][k];
}
arr = temp->arr;
//delete temp; -> doesn't work, valgrind tells that I free memory twice
}
array_xyz() {
rows = 0;
cols = 0;
arr = NULL;
}
~array_xyz() {
for (int i = 0; i < rows; i++)
delete []arr[i];
delete []arr;
}
【问题讨论】:
-
仅仅因为您要求您的 C++ 运行时释放内存,并不意味着它会立即释放到操作系统(页面中的其他分配可能也需要释放)。跨度>
-
1)
temp在构造函数完成时不会被释放。 2)arr = temp->arr;覆盖指向内存的指针,由arr = new double *[rows];分配,而不先释放它。 3) 为什么你还需要temp? -
arr最终会在你正在构造的对象的析构函数中被删除,因此删除temp(其中有相同的地址)将使析构函数中的free无效,并且所有之间的访问。
标签: c++ valgrind destructor delete-operator