Skip to content

Commit 57a7f68

Browse files
committed
Fix crash introduced by commit 447e579
It is not possible to use `next[0]` as the next pointer for the free list since we use the `next[0]` when freeing nodes. However, we can simplify the existing code significantly by ditching the free list approach entirely and just using a recursive function to free the tree.
1 parent 2719c47 commit 57a7f68

File tree

1 file changed

+11
-39
lines changed

1 file changed

+11
-39
lines changed

src/trie.c

+11-39
Original file line numberDiff line numberDiff line change
@@ -60,53 +60,25 @@ Trie *trie_new(void)
6060
return new_trie;
6161
}
6262

63-
static void trie_free_list_push(TrieNode **list, TrieNode *node)
63+
static void free_node_recursive(TrieNode *node)
6464
{
65-
node->next[0] = *list;
66-
*list = node;
67-
}
65+
int i;
6866

69-
static TrieNode *trie_free_list_pop(TrieNode **list)
70-
{
71-
TrieNode *result;
67+
if (node == NULL) {
68+
return;
69+
}
7270

73-
result = *list;
74-
*list = result->next[0];
71+
/* Free all subnodes */
72+
for (i = 0; i < 256; ++i) {
73+
free_node_recursive(node->next[i]);
74+
}
7575

76-
return result;
76+
free(node);
7777
}
7878

7979
void trie_free(Trie *trie)
8080
{
81-
TrieNode *free_list;
82-
TrieNode *node;
83-
int i;
84-
85-
free_list = NULL;
86-
87-
/* Start with the root node */
88-
if (trie->root_node != NULL) {
89-
trie_free_list_push(&free_list, trie->root_node);
90-
}
91-
92-
/* Go through the free list, freeing nodes. We add new nodes as
93-
* we encounter them; in this way, all the nodes are freed
94-
* non-recursively. */
95-
while (free_list != NULL) {
96-
node = trie_free_list_pop(&free_list);
97-
98-
/* Add all children of this node to the free list */
99-
for (i = 0; i < 256; ++i) {
100-
if (node->next[i] != NULL) {
101-
trie_free_list_push(&free_list, node->next[i]);
102-
}
103-
}
104-
105-
/* Free the node */
106-
free(node);
107-
}
108-
109-
/* Free the trie */
81+
free_node_recursive(trie->root_node);
11082
free(trie);
11183
}
11284

0 commit comments

Comments
 (0)