Reputation: 4237
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?
Upvotes: 0
Views: 3291
Reputation: 227548
When you delete resultTree
, you are deleting the memory passed to you from the function call to getNodeptree
. And you are failing to delete the memory from the explicit call to new.
func()
{
ptree *resultTree = new ptree; // you will need to delete this one
resultTree = &getNodeptree(pt); // now it points to something else!
delete resultTree; // now you delete something you shouldn't
}
Since getNodeptree
returns a reference, you really shouldn't be deleting that.
Upvotes: 4
Reputation: 96301
You do need to delete the memory, but you overwrite the address you allocated when you reassign the pointer in resultTree = &getNodeptree(pt);
. I can't understand what's supposed to be happening so I'm afraid I can't offer a suggestion at this time.
Upvotes: 2