使用C++类时出现巨大的删除错误
Huge deletion error using C++ classes
我正在用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
进行存储。它自动处理分配和解除分配。问题解决了。
相关文章:
- 将数组的地址分配给变量并删除
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- C/C++编译器通常会删除重复的库吗
- 从链接列表c++中删除一个项目
- C++如何通过用户输入删除列表元素
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 是否需要删除包含对象的"pair"?
- 如何在自删除后将对象设置为nullptr
- 迭代时从向量和内存中删除对象
- 使用函数"remove"删除重复元素
- 如何从多映射中删除特定的重复项
- 运算符C++ "delete []"仅删除 2 个前值
- 删除指向指针的指针是运行时错误吗
- 将指针设置为"nullptr"并不能防止双重删除?
- 为什么示例代码访问IUnknown中已删除的内存
- 如何通过 getter 函数删除矢量的元素?
- 在linux上调试巨大的C++项目
- 从控制台中删除最后打印的元素
- 使用C++类时出现巨大的删除错误
- 在c++中替换,添加和删除巨大文本文件中的行