Frage

EDIT: So I'm an idiot and forgot to SSH my updated .cpp when working with valgrind. Anyways I've updated the code below to represent new changes. Unfortunately I'm still getting some leaking with the stuff below and I'll I'm doing is creating a tree which means somewhere some information is still not being deleted properly.

Here is my destructor for my tree which calls the recursive helper.

//---------------------------- destructor --------------------------------
BinTree::~BinTree() {
    makeEmptyHelper(root);
}

//---------------------------- makeEmptyHelper --------------------------------
void BinTree::makeEmptyHelper(Node*& current) {

    if (current != NULL) {
        makeEmptyHelper(current->left);
        makeEmptyHelper(current->right);
        delete current->data;
        delete current;
        current = NULL;
        //delete current;
    }
}

Here is my node struct:

struct Node {
    NodeData* data; // pointer to data object 
    Node* left; // left subtree pointer 
    Node* right; // right subtree pointer 
};

NodeData is a separate object class that has its own destructor which works properly.

War es hilfreich?

Lösung

You should delete current before you set it to NULL, not afterwards. In fact, there is no reason to set current to NULL in the first place: the pointer current is passed by value, so updating it has no external effect.

Note that it is legal to delete NULL, but it is a no-op.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top