错误提出调试断言失败_BLOCK_TYPE_IS_VALID使用删除
问题描述:
我想在C++中的简单代码,但我在删除指针时出现Debug Assertion Failed _BLOCK_TYPE_IS_VALID
错误。我不知道我在做错什么。这是我的代码。错误提出调试断言失败_BLOCK_TYPE_IS_VALID使用删除
hash_map<string,string> m_hashDetails;
m_hashDetails.insert(hash_map<string,string>::value_type("test",*(new string("test123"))));
hash_map<string,string>::iterator myIterator;
myIterator = m_hashDetails.find("test");
if(myIterator == m_hashDetails.end())
{
printf("not found");
}
else
{
printf(myIterator->second.c_str());
//this is where I get Debug Assertion Failed _BLOCK_TYPE_IS_VALID
delete &(myIterator->second);
}
当我删除的hash_map
的second
场我得到Debug Assertion Failed _BLOCK_TYPE_IS_VALID
错误。我做错了什么?我使用new
运算符分配了second
字段?有一件事我注意到,如果我改变了hash_map定义 hash_map<string,string *> m_hashDetails;
和值插入像
m_hashDetails.insert(hash_map<string,string>::value_type("test",new string("test123")));
然后delete
不给错误..和工作正常?这个错误的实际原因是什么?
答
您已使用operator new
分配;但是你没有存储指针。而是你存储分配的块;
int *p = new int(1); // ok, can be deleted later
int i = *new int(1); // memory leaked already, cannot delete as pointer is missed
而且,std::string
不是指针类型,所以你不能delete
它。
所以你的情况,更改以下行,
*(new string("test123"))
到
string("test123")
那么你不必delete
它,因为std::string
自动释放的对象破坏。
感谢您的回答.. – 2011-05-10 07:33:32