Matteo Brini
Matteo Brini

Reputation: 183

How to free a tree struct using double pointer?

I have to free a tree and set his root to NULL using a particular function. I tried to use a recoursive method. But if I compile i get some warnings about "incompatible pointer type" and I'm not able to resolve it. This is the struct:

typedef struct node {
int key; 
struct node *left, *mid, *right;
} node_t;

And here the function. The first line cannot be changed:

void free_tree (node_t ** root){
if(root != NULL){
    free_tree((*root)->left);
    free_tree((*root)->mid);
    free_tree((*root)->right);
    free(*root);
    }
return;
}

Any help would be appreciated

Upvotes: 1

Views: 466

Answers (2)

WhozCraig
WhozCraig

Reputation: 66234

Your function expected a pointer to a pointer-to-node. You're giving it a pointer-to-node three times in your recursive calls. Further, you're not validating that the pointer-to-pointer, and the pointer it points to, are non-null; you're only validating the former.

In short, your function should look like this:

void free_tree (node_t ** root)
{
    if(root && *root)
    {
        free_tree(&(*root)->left);
        free_tree(&(*root)->mid);
        free_tree(&(*root)->right);
        free(*root);
        *root = NULL;
    }
}

The last functional line is optional, but frankly it's pointless to do this with pointers-to-pointers unless you're going to do that anyway, as it sets the caller's pointer to NULL after obliterating the tree. Given a properly built tree, your caller should deliver the address of the tree root when destroying the entire tree, as:

node_t *root = NULL;

// ... build tree ...

free_tree(&root);

// root is now NULL; tree is destroyed

Upvotes: 1

Yanis.F
Yanis.F

Reputation: 684

Your question cannot be answered very clearly but at least I can tell you why you have this warning about incompatible pointer type :

Your function prototype is

void free_tree (node_t ** root);

It's argument is a node_t **.

Your struct is

typedef struct node {
    int key; 
    struct node *left, *mid, *right;
} node_t;

So in your function :

void free_tree (node_t ** root)
{
    if(root != NULL)
    {
        free_tree((*root)->left);   <<< '(*root)->left' is of type 'node_t *'
        free_tree((*root)->mid);    <<< '(*root)->mid' is of type 'node_t *'
        free_tree((*root)->right);  <<< '(*root)->right' is of type 'node_t *'
        free(*root);
    }
    return;
}

You call you function giving a node_t * as argument whereas your function expects a node_t **

Upvotes: 1

Related Questions