I just started programming and I have a beginner question:
So I have a trie tree and I want to use it to store a large numbers of words from multiple files.
In order to do that everytime after I insert all the words from one file into the tree, I need to free the memory of the tree so that I can reuse the tree for the next file. Should I use free to just free the root? Or I need to traverse the tree and delete all the node one by one?
Here's the node, I am already able to insert all the words into the tree.
struct node{
struct node * parent;
int noempty;
int isword;
int super;
int occurrence;
int leaf;
struct node * child[26];
};
Here is my insert function:
struct node* insert(struct node *root,char *c){
int i=0;
struct node *temp=root;
int l=length(c);
while(i!=l){
int index=c[i]-'a';
if(temp->child[index]==NULL){
//New Node
struct node *n=(struct node *)malloc(sizeof(struct node));
n->parent=temp;
temp->child[index]=n;
temp->noempty=1;
}
//Node Exist
if(i!=l&&temp->leaf==1){temp->leaf=0;}
temp=temp->child[index];
i++;
}
if(temp->noempty==0){
temp->leaf=1;}
temp->isword=1;
return root;
};
You must traverse the tree and free every node. Each node you created for the Trie has been dynamically allocated. If you just delete the root, then only the memory for the root will be freed, while the memory for every other node is taking up space in the heap. This means you have a memory leak. If you create a Trie for each of your files, the memory that you have not freed could add up to be a substantial amount.