Skip to content

Commit

Permalink
Fix crash introduced by commit 447e579
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
fragglet committed Dec 17, 2024
1 parent 2719c47 commit 57a7f68
Showing 1 changed file with 11 additions and 39 deletions.
50 changes: 11 additions & 39 deletions src/trie.c
Original file line number Diff line number Diff line change
Expand Up @@ -60,53 +60,25 @@ Trie *trie_new(void)
return new_trie;
}

static void trie_free_list_push(TrieNode **list, TrieNode *node)
static void free_node_recursive(TrieNode *node)
{
node->next[0] = *list;
*list = node;
}
int i;

static TrieNode *trie_free_list_pop(TrieNode **list)
{
TrieNode *result;
if (node == NULL) {
return;
}

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

return result;
free(node);
}

void trie_free(Trie *trie)
{
TrieNode *free_list;
TrieNode *node;
int i;

free_list = NULL;

/* Start with the root node */
if (trie->root_node != NULL) {
trie_free_list_push(&free_list, trie->root_node);
}

/* Go through the free list, freeing nodes. We add new nodes as
* we encounter them; in this way, all the nodes are freed
* non-recursively. */
while (free_list != NULL) {
node = trie_free_list_pop(&free_list);

/* Add all children of this node to the free list */
for (i = 0; i < 256; ++i) {
if (node->next[i] != NULL) {
trie_free_list_push(&free_list, node->next[i]);
}
}

/* Free the node */
free(node);
}

/* Free the trie */
free_node_recursive(trie->root_node);
free(trie);
}

Expand Down

0 comments on commit 57a7f68

Please sign in to comment.