Antonis Petropoulos
Antonis Petropoulos

Reputation: 3

Delete whole binary tree from memory

I am working on a program that tests some functions and counts their elapsed time on binary search trees and to do these tests I've put these functions into a loop increasing the insertions for every circle. The problem is that since the trees take up memory , I have to free that memory so I've wroten a function to do it, but when I use it the resaults are the same as if I didn't; the RAM usage increases significantly.
Here is the function:

void deleteTree(treeNode* x){
    if(x){
        deleteTree(x->left);
        deleteTree(x->right);
        free(x->left);
        free(x->right);
    }
}

To create the nodes for the tree I use this structure:

typedef struct _treeNode{
    int key;
    struct _treeNode* left;
    struct _treeNode* right;
    struct _treeNode* parent;
}treeNode;

and this function:

treeNode* createTreeNode(int key){
    treeNode* a = (treeNode*)malloc(sizeof(struct _treeNode));
    a->key = key;
    a->left = NULL;
    a->right = NULL;
    a->parent = NULL;
    return a;
}

Upvotes: 0

Views: 83

Answers (2)

Doug Currie
Doug Currie

Reputation: 41220

You are operating one level off where you need to be. Try:

void deleteTree(treeNode* x){
    if(x){
        deleteTree(x->left);
        deleteTree(x->right);
        free(x);
    }
}

Upvotes: 2

H S
H S

Reputation: 1221

free () is used for freeing memory allocated by malloc () or alternatives; the chunk of allocated memory block is released to be used by next call of memory allocation but it doesn't clears memory. It just 'releases' it as in leaves it for further use and whatever happened to memory after freeing it, is implementation dependent.

Moreover, If you'd try to access freed memory you might get correct data but this behavior is undefined and often but not always results in Seg Fault.

Aforementioned reasoning explains little to no difference in execution time caused by free. As far as increase in RAM usage is concerned, this can be explained by OS's attempt at clubbing several 'free-d' chunks of memory.

Upvotes: 0

Related Questions