我是C++的新手。我收到堆损坏错误。任何帮助都将不胜感激。下面是我的代码
class CEntity
{
//some member variables
CEntity(string section1,string section2);
CEntity();
virtual ~CEntity();
//pure virtual function ..
virtual CEntity* create()const = 0;
}; 我从CLine派生自CEntity,如下所示
class CLine:public CEntity
{
// Again some variables ...
// Constructor and destructor
CLine(string section1,string section2);
CLine();
~CLine();
CLine* Create() const;
}
// CLine Implementation
CLine::CLine(string section1,string section2) : CEntity(section1,section2){};
CLine::CLine();
CLine* CLine::create() const {return new CLine();} 我有另一个类CReader,它使用CLine对象并将其填充到一个multimap中,如下所示
class CReader
{
public:
CReader();
~CReader();
multimap<int,CEntity*>m_data_vs_entity;
};
//CReader Implementation
CReader::CReader()
{
m_data_vs_entity.clear();
};
CReader::~CReader()
{
multimap<int,CEntity*>::iterator iter;
for(iter = m_data_vs_entity.begin();iter!=m_data_vs_entity.end();iter++)
{
CEntity* current_entity = iter->second;
if(current_entity)
delete current_entity;
}
m_data_vs_entity.clear();
} 我正在读取文件中的数据,然后将CLine Class.The映射填充到CReader类的函数中。因为CEntity有一个虚拟析构函数,所以我希望CReader析构函数中的代码能够工作。事实上,它确实适用于小文件,但我在处理更大的文件时会出现堆损坏错误。如果有什么根本的错误,那么,请帮助我找到它,因为我已经抓了我的头已经有一段时间了。
预先感谢,等待答复,
致以敬意,
阿图尔
继续从Y‘’day开始:深入研究这个问题,我现在已经意识到,在我的情况下,堆分配错误是因为我分配了一些东西,然后用更大的大小覆盖它。下面是在构造函数中填充数据的代码。
CEntity::CEntity(string section1,string section2)
{
size_t length;
char buffer[9];
//Entity Type Number
length = section1.copy(buffer,8,0);
buffer[length]='\0';
m_entity_type = atoi(buffer);
//Parameter Data Count
length = section1.copy(buffer,8,8);
buffer[length]='\0';
m_param_data_pointer = atoi(buffer);
//.... like wise ....
}我在固定的8个字符间隔内得到值,并添加一个'\0‘,因此,我猜这将处理我遇到的任何垃圾值。
关于堆分配错误:在XXX的普通块(XXX)之后,CRT检测到应用程序在堆缓冲区结束后写入内存。大多数情况下,堆分配错误发生在其他地方,而不是它崩溃的地方。如果这里有人能帮我,我会很感激你如何利用这个正常的街区和地址。谢谢,
发布于 2010-03-18 12:41:37
最后,经过两天的调试,我终于能够修复崩溃。这是因为我从字符串中复制了错误的字符数。
汲取的经验教训:
中生成的代码的质量。
谢谢您的帮助和格式化我的代码:)
致以敬意,
阿图尔
发布于 2010-03-15 12:11:35
好吧,你只展示了一半的问题。
创建CLine对象并将它们存储在CReader中的代码在哪里?
另外,您认为实际“拥有”CEntity对象是什么?一般来说,你应该让“所有者”负责创建和删除.
我早些时候写道:
“您可能会考虑将CEntitys直接存储在映射中,而不是存储指针。这可能会降低效率,但也会大大减少混乱的范围。”
正如尼尔所指出的,你要储存的不是CEntities,所以这个建议对你没有多大帮助。
https://stackoverflow.com/questions/2446839
复制相似问题