我在C ++中尝试一个简单的代码,但是当我删除指针时,我收到Debug Assertion Failed _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);
}
当我删除second
的{{1}}字段时出现hash_map
错误。我错了什么?我使用Debug Assertion Failed _BLOCK_TYPE_IS_VALID
运算符分配了second
字段?有一点我注意到,如果我将hash_map定义更改为
new
并插入
hash_map<string,string *> m_hashDetails;
然后m_hashDetails.insert(hash_map<string,string>::value_type("test",new string("test123")));
没有给出错误..并且工作正常?这个错误的实际原因是什么?
答案 0 :(得分:6)
您已使用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
会在对象销毁时自动释放。