[英]Freeing a trie tree
因此,我在網上找到了特里樹的一些示例,並專門嘗試了它們,以幫助我正在開發的游戲中包含字典中所有單詞的特里樹。 我在網上發現的示例沒有freeTree的任何實現,以避免內存泄漏,因此我嘗試自己創建一個。 但是我有一段時間沒有使用c了,遇到了問題。
char keys[][8] = {"the", "a", "there", "answer", "any",
"by", "bye", "their"};
char output[][32] = {"Not present in trie", "Present in trie"};
struct TrieNode *root = getNode();
// Construct trie
int i;
for (i = 0; i < ARRAY_SIZE(keys); i++){
insert(root, keys[i]);
}
// Search for different keys
printf("%s --- %s\n", "the", output[search(root, "the")] );
printf("%s --- %s\n", "these", output[search(root, "these")] );
printf("%s --- %s\n", "their", output[search(root, "their")] );
printf("%s --- %s\n", "thaw", output[search(root, "thaw")] );
freeTree(root);
printf("test after free\n");
printf("%s --- %s\n", "the", output[search(root, "the")] );
printf("%s --- %s\n", "these", output[search(root, "these")] );
printf("%s --- %s\n", "their", output[search(root, "their")] );
printf("%s --- %s\n", "thaw", output[search(root, "thaw")] );
這是一個正在運行的簡單測試,免費后的結果與之前相同
the --- Present in trie
these --- Not present in trie
their --- Present in trie
thaw --- Not present in trie
test after free
the --- Present in trie
these --- Not present in trie
their --- Present in trie
thaw --- Not present in trie
這是即時通訊使用的結構
struct TrieNode
{
struct TrieNode *children[ALPHABET_SIZE];
bool isLeaf;
};
和免費實施
void freeChildren(struct TrieNode *node){
int i;
if (node->isLeaf == false){
for (i=0;i<ALPHABET_SIZE;i++){
if (node->children[i] != NULL){
freeChildren(node->children[i]);
}
}
}
if (node != NULL){
node = NULL;
free(node);
}
}
void freeTree(struct TrieNode *root){
freeChildren(root);
free(root);
}
當我創建一個新的樹節點時,我為此分配了內存,因此我知道我需要釋放內存。
我認為您的問題是這部分:
if (node != NULL){
node = NULL;
free(node);
}
好吧,您需要釋放它,然后將其設置為NULL。 否則,您已經丟失了地址。
void freeChildren(struct TrieNode *node){
int i;
if (node != NULL && node->isLeaf == false){//NULL check important only for the root
for (i=0;i<ALPHABET_SIZE;i++){
if (node->children[i] != NULL){
freeChildren(node->children[i]);
node->children[i] = NULL]; //you have to remove the address, otherwise it stays, just is no longer allocated (but it is still possible to access it, though it might crash or do whatever else)
}
}
}
if (node != NULL){ //again only root could be NULL
free(node);//this has to go first
//node = NULL; this has no meaning, as this is the local variable, not the place you passed it to
}
}
void freeTree(struct TrieNode *root){
freeChildren(root);
// free(root); this is already done in the freeChildren
// you might want to realloc the root there though, as otherwise you don't have anything allocated to root
root = NULL;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.