c++ - double free or corruption (out) when trying to delete Nodes in a Binary tree -
i'm trying make recursive function delete nodes in binary tree, p->left , p->right pointers next level in tree. gives following error message:
* error in `./test.out': double free or corruption (out): 0x00007ffdf0cb3650 *
struct node { int key; double data; node * right; node * left; }; void delete_tree(node * & p){ if (p->left){ delete_tree(p->left); } if (p->right){ delete_tree(p->right); } delete p; }; int main(){ node * currentnod = new node; currentnod->key = 5; node * newnode = new node; newnode->key = 3; node * newnode2 = new node; newnode2->key = 6; delete_tree(currentnod); std::cout << currentnod->key << "\n"; std::cout << newnode->key << "\n"; std::cout << currentnod->left->key << "\n"; return 0;
i've searched online , realize there can problems when have recursive functions pointers, delete_tree takes reference, not copy, problem should not apply here? don't understand why it's not working :(
edit: changed code, problem when initializing currentnod first created node object, , let currentnod pointer object. when instead initialize this, works. however, not print expect. prints:
0 3 segmentation fault
when expect give segmentation fault right away. have idea problem now? :)
it make lot more sense recast destructor:
class node { public: // constructor, methods, ... // destructor ~node(); private: int key; double data; node * right; node * left; }; node::~node(){ delete left; delete right; left = right = nullptr; // see note below };
then need delete node;
wherever want delete tree. if it's subtree need ensure parent's pointer node nulled don't double-delete.
Comments
Post a Comment