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?
A couple things:
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With