[英]Error raised Debug Assertion Failed _BLOCK_TYPE_IS_VALID when delete is used
我正在尝试使用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);
}
当我删除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
在对象销毁时会自动释放。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.