使用删除时引发错误Debug Assertion失败_BLOCK_TYPE_IS_VALID

时间:2011-05-10 06:09:10

标签: c++ new-operator assertions delete-operator

我在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"))); 没有给出错误..并且工作正常?这个错误的实际原因是什么?

1 个答案:

答案 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会在对象销毁时自动释放。