2011-05-10 86 views
0

我想在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_mapsecond场我得到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不给错误..和工作正常?这个错误的实际原因是什么?

回答

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自动释放的对象破坏。

+0

感谢您的回答.. – 2011-05-10 07:33:32