user1701884
user1701884

Reputation: 13

How to free a binary tree using C?

I have written a binary search tree, it works fine but I'm not sure whether my program frees all the memories.

here is my definition of the node of a tree

typedef struct node  {
    int val;
    struct node *left, *right;
} nodeOfTree;

I write this function to output the result and free all the nodes, it seems that the answer is right but the memories are not freed.

void outputAndDestroyTree(nodeOfTree *root)  {
    if (!root) {return;}
    outputAndDestroyTree(root->left);
    printf("%d ", root->val);
    outputAndDestroyTree(root->right);
    free(root);      // I free this pointer, but after doing that, I can still access this  pointer in the main() function
}

Is that mean I can not free a piece of memories in the recursive function? Thank you ~~~~~

Update: Thank you all~

Upvotes: 1

Views: 8733

Answers (1)

Havenard
Havenard

Reputation: 27894

Your code seems okay, but freeing the allocated memory won't magically set it's reference pointer to NULL. Since you didn't set a new value to the pointer, the old address will remain there, untouched. Maybe you can even read from it without crashing, despite it being undefined behavior.

If you want it to be set to NULL after freeing the memory, then just do so. Call outputAndDestroyTree(root->left); then do root->left = NULL;.

Upvotes: 5

Related Questions