使用C++类时出现巨大的删除错误

Huge deletion error using C++ classes

本文关键字:巨大 删除 错误 C++ 使用      更新时间:2023-10-16

我正在用c++构建一个图像分析程序。它接收一个保存值的文本文件,以构建灰度图像。我用差的平方和来找出这张图中的一个特定块。。这是使用头文件中的矩阵类构建的,所以我有两个重载的构造函数和一个析构函数,它删除指向double的指针,该指针为这个巨大的值数组(768 x 1024)在堆上分配内存。然而,这抛出了一个内存错误;调试断言失败,表达式:块类型有效。我不明白为什么会发生这种事。。为了进行SSD计算,我使用两个for循环;操作两个矩阵对象,其中一个修正调用其中一个构造函数,通过从较大的矩阵对象中获取块来创建新的矩阵对象。我知道当对象超出范围时,析构函数在每个循环中被调用两次?这是双重删除吗?为什么会出现错误?下面是我的构造函数和循环。如果有人能理解我为什么会犯这个错误,我会非常高兴。

施工单位:

// Matrix constructor creating a new matrix object where all elements are the same number
Matrix::Matrix(int sizeR, int sizeC, double val)
{
//cout << "Matrix(int sizeR, int sizeC, double val) is invoked.." << endl;
M = sizeR;
N = sizeC;
data = new double[M * N];// Initialise space for class array 'data'
for (int i = 0; i < M* N; i++)
{
data[i] = val;// Set each element of the array to the same value passed to the constructor from main
}
}
// Matrix constructor taking pointer to array as input; creates a new matrix object
Matrix::Matrix(int sizeR, int sizeC, double* input_data)
{
//cout << "Matrix::Matrix(int sizeR, int sizeC, double* input_data) is invoked...." << endl;
M = sizeR;
N = sizeC;
data = new double[M * N];// Initialise space for class array 'data'
for (int i = 0; i < M * N; i++)
{
data[i] = input_data[i];// Set elements in data as elements from input_data passed to the constructor from main
}
}

破坏者:

// Matrix destructor
Matrix::~Matrix()
{
//cout << "Matrix::~Matrix() is invoked..." << endl;
delete data;
}

主要代码:

for (int i = 0; i < (768 - 21); i++)
{
for (int j = 0; j < (1024 - 21); j++)
{
counter++;
clutteredBlock = cluttered.getBlock(i, (i + 21), j, (j + 21));
diff = clutteredBlock - wallyBlock;
diff = diff * diff;
tempVal = diff.Sum();
if (i == 0 && j == 0)
{
ssd = tempVal;
}
if (tempVal <= ssd)
{
ssd = tempVal;
co1 = i;
co2 = j;
}
}
}

所以M、N和data都是私有类成员;M和N是CCD_ 1,数据是double*;数据是我试图删除的指针,但却一无所获。

更新:如果我忽略了这个错误,我就会得到一个HEAP CORRUPTION错误,说我试图在缓冲区之后写入堆?

UPDATE:赋值运算符;

Matrix& Matrix::operator=(const Matrix& input)
{
//cout << "Matrix::operator= is invoked..." << endl;
if (this == &input)
{
return *this;
}
else
{
delete data;
M = input.getR();
N = input.getC();
data = new double[M * N];
for (int i = 0; i < M; i++)
{
for (int j = 0; j < N; j++)
{
Set(i, j, input.Get(i, j));
}
}
}
return *this;
}

非常感谢任何输入:)

使用std::vector进行存储。它自动处理分配和解除分配。问题解决了。