Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: Freeing Binary Search Tree

I have this code:

node* free_tree(node *root){

  if(root != NULL){

    free_tree(root->left);
    free_tree(root->right);

    free(root->name);
    free(root);
  }
  return NULL;
}

I know this isn't correct, correct version is with:

root -> left = free_tree(root->left);
root -> right = free_tree(root->right);

What I don't understand is, why does this work? When I return from free_tree(root->left) with NULL, my function require that some node* receive NULL value, this is not the case here, so I don't get it, why does this work? Why is this not a compilation error?

like image 664
Aleksandar Makragić Avatar asked Jan 07 '23 19:01

Aleksandar Makragić


1 Answers

A couple things:

  1. There's no reason why this function needs to return anything. The second version you show uses the return value to update the left and right pointers prior to freeing them, but (a) There's no need to since you're freeing the node anyway, and (b) The value is always NULL. Since it's a constant, there's no reason to return it.

  2. There's no compilation error because there are no type violations. The only issue is that you're calling a function that returns a node * but aren't using the return value. However, that's legal C.

like image 65
Tom Karzes Avatar answered Jan 17 '23 10:01

Tom Karzes