I’m confused as to why after I have created a pointer and try to delete it I receive and error message. The following is some condensed code I’ve been working with:
func()
{
ptree *resultTree = new ptree;
resultTree = &getNodeptree(pt);
delete resultTree;
}
ptree& getNodeptree (ptree &pt)
{
BOOST_FOREACH(ptree::value_type &v, pt.get_child("root"))
{
ptree &temp = v.second;
return temp;
}
}
From my understanding resultTree still needs to be deleted because it’s memory is still on the heap. However, trying to do that produces:
*** glibc detected *** /home/nathan/Programming/Project_Code/MyBoostXmlTest/Debug/MyBoostXmlTest: free(): invalid pointer: 0x00000000018347b8 ***
Can someone explain why calling delete produces an error in this instance?
When you delete
resultTree, you are deleting the memory passed to you from the function call togetNodeptree. And you are failing to delete the memory from the explicit call to new.Since
getNodeptreereturns a reference, you really shouldn’t be deleting that.