harvey_slash harvey_slash - 8 months ago 32
C Question

Not able to free memory from function

I have a C program that implements trees. my cleanup function looks like this :

void cleanup_tree( TreeNode* root ){


if(root->right!= NULL){

if(root->right==NULL &&root->left==NULL) {
root = NULL;


My Tree struct has

typedef struct TreeNode_st {
char *word; // the word held in this node
unsigned int frequency; // how many times it has been seen
struct TreeNode_st *left; // node's left child
struct TreeNode_st *right; // node's right child
} TreeNode;

I am initialising a tree like this :

TreeNode* initTreeNode(){
TreeNode *mainNode= (TreeNode*)malloc(sizeof(TreeNode));
mainNode->frequency = 0 ;
mainNode->word = NULL;
mainNode->left = NULL;
mainNode->right = NULL;
return mainNode;


in my main, I have called

TreeNode *mainNode =initTreeNode();

and im doing operations on it , and just before program exit, i called


Valgrind reported memory leaks, so just to test , i did
I put

printf("~~~FINAL NULL TEST %s",mainNode->left->right->word);

below my cleanup_tree line,
And i'm able to see the word even now.

What am i doing wrong ?


There are two ways:

  1. You pass it a pointer-to-a-pointer: void cleanup_tree( TreeNode **root)
  2. You set the fields to NULL after the cleanup returns:

Currently, the changes made by the function are not reflected in the node parameter you passed.

Ad 2:

root->right= NULL;