运行以下程序时出现此错误(它完美地执行代码,但看起来有一些关于指针/内存的问题)。提前感谢您的帮助...
这是我得到的信息:
REVIEW(8310)malloc: *对象0x100103b80的错误:未释放指针被释放 * 在malloc_error_break中设置断点以进行调试 (lldb)
我的代码:
在文件Matrix.h中
template <typename T>
class Matrix
{
private:
T** M;
// unsigned numCol, numRow;
unsigned minRowIndex, maxRowIndex;
unsigned minColIndex, maxColIndex;
public:
Matrix(); // default constructor
Matrix(const unsigned& _numRow,
const unsigned& _numCol,
const T& value,
const unsigned& _minRowIndex = 0,
const unsigned& _minColIndex = 0);
~Matrix();
void Print();
T& operator() (const unsigned& row, const unsigned& col);
};
template<typename T>
Matrix<T> :: Matrix()
{
maxRowIndex = 9;
maxColIndex = 9;
unsigned i,j;
M = new T*[maxRowIndex + 1];
for (i = minRowIndex; i < maxRowIndex; i++)
M[i] = new T[maxColIndex + 1];
for (i = minRowIndex; i < maxRowIndex; i++)
for (j = minColIndex; j < maxColIndex; j++)
M[i][j] = 0;
}
template<typename T>
Matrix<T> :: Matrix( const unsigned& _numRow,
const unsigned& _numCol,
const T& value,
const unsigned& _minRowIndex,
const unsigned& _minColIndex)
{
minRowIndex = _minRowIndex;
minColIndex = _minColIndex;
maxRowIndex = _minRowIndex + _numRow - 1;
maxColIndex = _minColIndex + _numRow - 1;
unsigned i,j;
M = new T*[maxRowIndex + 1];
for (i = minRowIndex; i <= maxRowIndex; i++)
M[i] = new T[maxColIndex + 1];
for (i = minRowIndex; i <= maxRowIndex; i++)
for (j = minColIndex; j <= maxColIndex; j++)
M[i][j] = value;
}
template<typename T>
Matrix<T> :: ~Matrix()
{
for (unsigned i = 0; i <= maxRowIndex; i++)
delete[] M[i];
delete[] M;
}
template<typename T>
void Matrix<T> :: Print()
{
unsigned i,j;
for (i = minRowIndex ; i <= maxRowIndex; i++)
for (j = minColIndex; j <= maxColIndex; j++)
{
cout << M[i][j] << " ";
if (j == maxColIndex)
cout << endl;
}
cout << endl;cout << endl;
}
template<typename T>
T& Matrix<T> :: operator() (const unsigned& row, const unsigned& col)
{
return M[row][col];
}
在文件main.cpp中
#include "Matrix.h"
using namespace std;
int s(Matrix<int> L)
{
return L(2,2);
}
int main()
{
Matrix<int> L (5,5,100);
cout << "L(2,2) = " << s(L) << endl << endl;
return 0;
}
答案 0 :(得分:0)
使用new
和delete
分配字段的类应具有复制构造函数和重载operator=
。如果不这样做,将使用默认表单,其中只复制字段。
在您的情况下,T** M
在调用s(L)
期间被复制,并且在返回时,副本被破坏,导致删除所有数组。在main的末尾,发生了另一次破坏,但现在指针指的是已经释放的块。
对于函数s
,您也可以传递引用以避免复制(但这不能解决一般问题)。