cdata-structuresmallocbinary-treefree

Using free() with data structures


I am not from a computer science background and have been trying to learn Data Structures using C programming.

I have made some binary tree programs and realised that I have used malloc() left and right (pun intended :)) without ever using free() because I don't know how many nodes I have actually created.

My question is rather basic and almost stupid. Do I have to write a function similar to the print function to visit each node of the tree and free it individually or just free(root) will be enough since all the subsequent pointers will be lost anyway?


Solution

  • When using malloc() in C to allocate memory for nodes in a binary tree, calling free(root) will not automatically free the memory of the child nodes. The tree structure consists of pointers, so while root will be freed, the left and right child pointers may still point to memory that has not been deallocated.

    To properly free all the nodes, you should traverse the tree and free each node individually. This is typically done using a post-order traversal (where you visit the left and right children before freeing the current node).

    example of how you might implement this:

    void freeTree(struct Node* root) {
        if (root == NULL)
            return;
    
        freeTree(root->left);  // Free left subtree
        freeTree(root->right); // Free right subtree
        free(root);            // Free current node
    }
    

    Note:
    if the binary tree is highly unbalanced (i.e., resembling a linked list), this recursive approach could lead to a stack overflow due to deep recursion. In such case we can use an iterative approach, such as using a stack to simulate the recursive calls, or by flattening the tree into a linked list structure and freeing the nodes iteratively.