【问题标题】:Error raised Debug Assertion Failed _BLOCK_TYPE_IS_VALID when delete is used使用删除时引发错误调试断言失败_BLOCK_TYPE_IS_VALID
【发布时间】:2011-05-10 06:09:09
【问题描述】:

我正在尝试使用 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&lt;string,string *&gt; m_hashDetails; 并插入类似的值

m_hashDetails.insert(hash_map<string,string>::value_type("test",new string("test123")));

然后delete 没有给出错误.. 并且工作正常?这个错误的真正原因是什么?

【问题讨论】:

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


    【解决方案1】:

    您已使用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在对象销毁时会自动释放。

    【讨论】:

      猜你喜欢
      • 2012-01-11
      • 1970-01-01
      • 2010-11-09
      • 1970-01-01
      • 1970-01-01
      • 2012-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多