Skip to content

Commit a34de70

Browse files
committed
Add freetable() function.
freetable() 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 bfb23a6 commit a34de70

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

chapter06/6-5.c

+16
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ char *strDup(char *);
2222
struct nlist *lookup(char *);
2323
struct nlist *install(char *, char *);
2424
void undef(char *);
25+
void freetable(struct nlist *[], int);
2526

2627
/* globals */
2728
static struct nlist *hashtab[HASHSIZE]; /* pointer table */
@@ -94,6 +95,19 @@ void undef(char *s)
9495
}
9596
}
9697

98+
/* freetable: free table's (and its content's) allocated memory from heap */
99+
void freetable(struct nlist *node[], int size)
100+
{
101+
int i;
102+
103+
for (i = 0; i < size; i++)
104+
if (node[i] != NULL) {
105+
free(node[i]->name);
106+
free(node[i]->defn);
107+
free(node[i]);
108+
}
109+
}
110+
97111
int main(void)
98112
{
99113
struct nlist *p;
@@ -118,5 +132,7 @@ int main(void)
118132
if (hashtab[i] != NULL)
119133
printf("%i name: %s defn: %s\n",
120134
i, hashtab[i]->name, hashtab[i]->defn);
135+
136+
freetable(hashtab, HASHSIZE); /* clean up */
121137
return 0;
122138
}

chapter06/6-6.c

+15
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ char *strDup(char *);
4949
unsigned hash(char *);
5050
struct nlist *lookup(char *);
5151
struct nlist *install(char *, char *);
52+
void freetable(struct nlist *[], int);
5253

5354
/* binsearch: find word in tab[0]...tab[n - 1] */
5455
struct key *binsearch(char *word, struct key *tab, int n)
@@ -218,6 +219,19 @@ struct nlist *install(char *name, char *defn)
218219
return np;
219220
}
220221

222+
/* freetable: free table's (and its content's) allocated memory from heap */
223+
void freetable(struct nlist *node[], int size)
224+
{
225+
int i;
226+
227+
for (i = 0; i < size; i++)
228+
if (node[i] != NULL) {
229+
free(node[i]->name);
230+
free(node[i]->defn);
231+
free(node[i]);
232+
}
233+
}
234+
221235
/* simple define processor (no arguments) */
222236
int main (void)
223237
{
@@ -246,5 +260,6 @@ int main (void)
246260
if (hashtab[i] != NULL)
247261
printf("%i name: %s defn: %s\n",
248262
i, hashtab[i]->name, hashtab[i]->defn);
263+
freetable(hashtab, HASHSIZE); /* clean up */
249264
return 0;
250265
}

0 commit comments

Comments
 (0)