调试断言失败!错误的内存释放
Debug Assertion Failed! Wrong memory freeing
>我有一个问题,在使用动态分配的内存进行处理时出现。我一直在寻找类似的问题,但不幸的是,没有任何解决方案帮助我。我的类的代码如下所示:
我的班级声明:
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;
}
但是告诉我,当我使用复制构造函数时?我想我从来没有基于现有创建新对象?
相关文章:
- 包含矢量指针的结构的内存释放问题
- Valgrind 声称内存释放中的自由空间太多
- 当 C 和 C++ 中严格要求内存释放时
- C++ 中指针变量的内存释放
- 德克内存释放
- 临时对象 c++ 的内存释放
- C 全局对象变量内存释放
- C++矢量动态内存释放/删除
- 从 cv::Mat 初始化的 IplImage 的内存释放
- SWIG类型映射中的内存释放
- STL容器中的内存释放
- QWebView内存释放
- 内存释放 C++
- 大返回值(如字符串)的内存释放如何在C++中发生
- 重新分配之前的内存释放
- Linux C++ 中的内存释放
- VS2012编译器奇怪的内存释放问题
- 调试断言失败!错误的内存释放
- 负责 COM 互操作中的内存释放
- imread命令后OpenCV矩阵内存释放