Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

freeing memory of a binary tree C

I would like to free memory from my allocated binary tree what traversal is the best for doing so?

typedef struct Node{
struct Node * right;
struct Node * left;
void * data;
}Node;


typedef int (*cmp) (void*,void *);


Node* init(void * element){
    Node * newNode=(Node*)malloc(sizeof(Node));
    newNode->data=element;
    newNode->left=NULL;
    newNode->right=NULL;
    return newNode; 
}

void  insert(void * element, Node** root,cmp compareTo){
    if(*root==NULL){
        *root=init(element);
        return;
    }
    if(compareTo(element,(*root)->data)==1)
        insert(element,&((*root)->left),compareTo);
    else
        insert(element,&((*root)->right),compareTo);
}
like image 468
mary Avatar asked Feb 07 '12 17:02

mary


2 Answers

Since it's a tree, you should go with a recursive approach.

deallocate (node):
    //do nothing if passed a non-existent node
    if node is null
        return

    //now onto the recursion
    deallocate(left node)
    deallocate(right node)

    free node
like image 179
Pochi Avatar answered Sep 19 '22 13:09

Pochi


void free_tree(Node * node){
   //post-order like FatalError hinted at
       if (node != NULL) {
        free_tree(node->right);
        free(node->data); //if data was heap allocated, need to free it
        free_tree(node->left);
        free(node);
     }}

A cool way to check seg faults and memory leaks is to use

valgrind --leak-check=full ./yourProgram

like image 28
MrPickles7 Avatar answered Sep 21 '22 13:09

MrPickles7