调试断言失败!错误的内存释放

Debug Assertion Failed! Wrong memory freeing

本文关键字:内存 释放 错误 断言 失败 调试      更新时间:2023-10-16

>我有一个问题,在使用动态分配的内存进行处理时出现。我一直在寻找类似的问题,但不幸的是,没有任何解决方案帮助我。我的类的代码如下所示:

我的班级声明:

class StructuralElement
{
    private:
    short rows;
    short columns;
    short *se;
    friend class Morph;
public:
    StructuralElement(char *path);
    ~StructuralElement();
    short getAt(short row, short column);
    int getSize();
};

我的类的定义:

StructuralElement::StructuralElement(char *path)
{
std::string line;
short rows=0, elements=0;
short it = 0;
std::string token;
try
{
    std::ifstream file(path);                   //counting rows and columns in a file!
    if (file.is_open() == NULL){ CannotOpenException ex; throw ex; }
    if (file.fail()) { CannotOpenException ex; throw ex; }
    while (getline(file,line))
    {
        rows++;
        std::stringstream ss(line);
        while (getline(ss, token, ' '))
        {
            elements++;
        }
    }
    file.close();
    this->rows = rows;
    if (rows!=0)
    this->columns = (elements/rows);
    se = new short[elements];
    std::ifstream file2(path);
    if (!file2.is_open()) throw;
    while (getline(file2, line))
    {
        std::stringstream ss(line);
        while (getline(ss, token, ' '))
        {
            this->se[it++] = (static_cast<int>(token.at(0))-48);        
        }
    }
    file2.close();
}
catch (CannotOpenException &ex)
    {
    std::cerr << "Error occured! Unable to load structural element!";
    }
}
StructuralElement::~StructuralElement()
{
    if (se != NULL) delete[] se;
}

当程序已经完成工作并出现文本:"Cick any key...."在控制台中,然后我收到错误:

调试断言失败

.......

表达式:_BLOCK_TYPR_IS_VALID(pHeap->nBlockUse)

当我换行时 se = 新的短[元素];对此: se = 新短 [];
然后我收到消息:程序在断点中触发。

我做错了什么?提前感谢您的任何提示。

您很有可能

正在执行双重删除。

您的类没有复制构造函数或赋值运算符,但您正在以非 RAII 方式管理资源。这很可能是问题的原因。实现适当的复制构造函数和赋值运算符,该运算符实际创建数据成员的深层副本。

Timo-好消息!创建复制构造函数解决了我的问题。非常感谢你,因为我被困在这个地方。再次感谢。这是一个代码:

 StructuralElement::StructuralElement(const StructuralElement &obj)
    {
        short *newse = new short[obj.columns*obj.rows];
        for (int i = 0; i < obj.columns*obj.rows; i++)
            newse[i] = obj.se[i];
        this->rows = obj.rows;
        this->columns = obj.columns;
        this->se = newse;
    }

但是告诉我,当我使用复制构造函数时?我想我从来没有基于现有创建新对象?