Skip to content

Commit 61699bf

Browse files
committed
Add freetree() and freelist().
freetree and freelist free the allocated heap memory manually rather than relying on the OS for garbage collection. This avoid potential memory leak issues, which is good practice.
1 parent a34de70 commit 61699bf

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

chapter06/6-3.c

+26
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,8 @@ struct tnode *addtree(struct tnode *, char *, int);
5252
void treeprint(struct tnode *);
5353
void printList(struct list *);
5454
struct key *binsearch(char *, struct key *, int);
55+
struct tnode *freetree(struct tnode *);
56+
struct list *freelist(struct list *);
5557

5658
/* globals */
5759
char buf[BUFSIZE]; /* buffer from ungetch */
@@ -188,6 +190,29 @@ struct key *binsearch(char *word, struct key *tab, int n)
188190
return NULL;
189191
}
190192

193+
/* freellist: frees allocated heap memory of linked list */
194+
struct list *freelist(struct list *node)
195+
{
196+
if (node->next != NULL) {
197+
freelist(node->next);
198+
free(node);
199+
}
200+
return node;
201+
}
202+
203+
/* freetree: frees allocated heap memory of tree */
204+
struct tnode *freetree(struct tnode *node)
205+
{
206+
if (node != NULL) {
207+
freetree(node->left);
208+
freetree(node->right);
209+
free(node->word);
210+
freelist(node->line); /* delete linked list nodes */
211+
free(node->line); /* delete linked list */
212+
free(node);
213+
}
214+
return node;
215+
}
191216
int main(void)
192217
{
193218
struct tnode *root; /* root node */
@@ -206,5 +231,6 @@ int main(void)
206231
root = addtree(root, word, lineNumb);
207232
}
208233
treeprint(root);
234+
root = freetree(root); /* clean up */
209235
return 0;
210236
}

0 commit comments

Comments
 (0)