【发布时间】:2010-03-15 11:54:03
【问题描述】:
我是 C++ 新手。我收到堆损坏错误。任何帮助将不胜感激。下面是我的代码
class CEntity
{
//some member variables
CEntity(string section1,string section2);
CEntity();
virtual ~CEntity();
//pure virtual function ..
virtual CEntity* create()const = 0;
};
我从 CEntity 派生 CLine 如下
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 对象并将其填充到如下所示的多映射中
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 类。地图被填充到 CReader 类的函数中。由于 CEntity 有一个虚拟析构函数,我希望 CReader 的析构函数中的这段代码应该可以工作。事实上,它确实适用于小文件,但是在处理更大的文件时我得到了 HEAP CORRUPTION ERROR。如果有什么根本性的错误,那么,请帮我找到它,因为我一直在挠头想退出。
在此先感谢并等待回复,
问候,
阿图尔
从 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 检测到应用程序在堆缓冲区结束后写入内存。 大多数情况下,堆分配错误发生在崩溃的其他地方。如果这里有人能帮助我,我将不胜感激,如何使用这个普通块和地址。 谢谢,
【问题讨论】:
-
是实际代码吗?如果是这样,为什么
create是非静态成员函数?它应该如何使用? -
您能否向我们展示填充
m_data_vs_entity的代码,因为我感觉您可能会将同一个指针两次放入地图中。 -
@Naveen,我认为他的
create()是虚拟构造函数的一个例子——它不应该是静态的。 -
@Poita_:是的,你是对的。我忘记了。
-
bool CReader::process_entity(string section1,string section2) { size_t length;字符缓冲区[9]; //1.Entity Type Number length = Section1.copy(buffer,8,0);缓冲区[长度]='\0'; int ent_type = atoi(缓冲区); CEntity* current_ent = NULL; switch(ent_type) { case 110: CLine* line_entity = new CLine(Section1,Section2); current_ent = line_entity;休息;默认值:{中断; } } if(current_ent != NULL) { int PD_Pointer = current_ent->get_parameter_data_ptr(); // 为链接填充映射和多映射 ... m_data_vs_entity.insert(pair
(PD_Pointer,current_ent)); } 返回真; }
标签: c++ memory-management