我有一个动态重新分配大小的矩阵类。具体来说:动态重新分配行数组。
但在某些情况下,调用矩阵的析构函数时会出现内存释放问题:
*** 检测到 glibc *** ./solver: free(): invalid next size (fast): 0x0000000000c112b0 ***
并且该过程正在中止。
矩阵类:
#ifndef __matrix_hpp
#define __matrix_hpp
#include <cstring>
#include <stdexcept>
#include "row.hpp"
using namespace std;
class Matrix {
public:
Matrix();
~Matrix();
size_t size();
void resize(size_t size);
double get(size_t x, size_t y) throw (out_of_range);
void set(size_t x, size_t y, double value) throw (out_of_range);
double getfv(size_t y) throw (out_of_range);
void setfv(size_t y, double value) throw (out_of_range);
void optimize(size_t y) throw (out_of_range);
void _print();
private:
size_t sz;
Row **data;
};
#endif
和身体的重要功能:
Matrix::~Matrix() {
if (data != NULL) {
for (size_t i = 0; i < sz; ++i)
delete data[i];
delete [] data;
}
}
void Matrix::resize(size_t size) {
if (size == sz)
return;
Row **newData = new Row *[size];
if (data != NULL)
memcpy(newData, data, sz * sizeof(Row*));
if (size > sz) {
for (size_t i = sz; i < size; ++i)
newData[i] = new Row();
}
else {
for (size_t i = size; i < sz; ++i)
delete data[i];
}
delete [] data;
data = newData;
sz = size;
}
所以,这就是代码。当我制作一个矩阵然后减小它的大小并调用析构函数时,问题就来了。例如:
Matrix *matrix = new Matrix();
matrix->resize(10);
matrix->resize(7);
delete matrix;
但是使矩阵更大的效果很好:
Matrix *matrix = new Matrix();
matrix->resize(10);
matrix->resize(13);
delete matrix;
最有趣的是,这个例子有效:
Matrix *matrix = new Matrix();
matrix->resize(3);
matrix->resize(2);
delete matrix;
所以我不知道有什么问题。有什么建议么?