Skip to content

Commit ac885ab

Browse files
committed
Add freetree().
freetree() frees 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 61699bf commit ac885ab

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

chapter06/6-2.c

+13
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ struct tnode *talloc(void); /* alocate memory to new tree node */
2626
char *strDup(char *); /* copy string into safe place */
2727
struct key *binsearch(char *, struct key *, int);
2828
void findVariables(struct tnode *, int);
29+
struct tnode *freetree(struct tnode *);
2930

3031
/* globals */
3132
char buf[BUFSIZE]; /* buffer from ungetch */
@@ -196,6 +197,17 @@ struct tnode *talloc(void)
196197
return (struct tnode *) malloc(sizeof(struct tnode));
197198
}
198199

200+
/* freetree: free allocated heap memory of node tree */
201+
struct tnode *freetree(struct tnode *node)
202+
{
203+
if (node != NULL) {
204+
freetree(node->left);
205+
freetree(node->right);
206+
free(node->word);
207+
free(node);
208+
}
209+
return node;
210+
}
199211
/*strDup: make a duplicate of s */
200212
char *strDup(char *s)
201213
{
@@ -264,5 +276,6 @@ int main(int argc, char *argv[])
264276
root = addtree(root, word); /* reserved words */
265277
findVariables(root, nChar);
266278
treeprint(root);
279+
root = freetree(root); /* clean up */
267280
return 0;
268281
}

chapter06/6-4.c

+16-2
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ struct tnode *addtree(struct tnode *, char *);
2727
void treeprint(struct tnode *);
2828
struct tnode *copyTree(struct tnode *, struct tnode *);
2929
struct tnode *sortTree(struct tnode *, struct tnode *);
30+
struct tnode *freetree(struct tnode *);
3031

3132
/* globals */
3233
char buf[BUFSIZE]; /* buffer from ungetch */
@@ -134,13 +135,24 @@ struct tnode *copyTree(struct tnode *p, struct tnode *root)
134135
struct tnode *sortTree(struct tnode *p, struct tnode *root)
135136
{
136137
if (root != NULL) {
137-
sortTree(p, root->left);
138+
p = sortTree(p, root->left);
138139
p = copyTree(p, root);
139-
sortTree(p, root->right);
140+
p = sortTree(p, root->right);
140141
}
141142
return p;
142143
}
143144

145+
/* freetree: free allocated heap memory of node tree */
146+
struct tnode *freetree(struct tnode *node)
147+
{
148+
if (node != NULL) {
149+
freetree(node->left);
150+
freetree(node->right);
151+
free(node->word);
152+
free(node);
153+
}
154+
return node;
155+
}
144156
int main(void)
145157
{
146158
struct tnode *root; /* root node */
@@ -154,5 +166,7 @@ int main(void)
154166
root = (addtree(root, word));
155167
sRoot = sortTree(sRoot, root);
156168
treeprint(sRoot);
169+
root = freetree(root); /* clean up */
170+
sRoot = freetree(sRoot); /* clean up */
157171
return 0;
158172
}

0 commit comments

Comments
 (0)