2016-10-29 17 views
0

所以我發現在網上特里樹的一些例子,除冰嘗試一下,以幫助遊戲IM上的工作將包含在字典中的所有單詞特里樹樹。我在網上找到的例子沒有一個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; 
}; 

結構IM和自由實現

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); 
} 

瓦我創建一個新的樹節點我malloc它的內存,所以我知道我需要釋放。

回答

1
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; 
} 
+0

感謝您的答覆,現在的作品!意見非常明確,內容翔實,謝謝! – user3267256

2

我覺得你的問題是這樣的部分:

if (node != NULL){ 
    node = NULL; 
    free(node); 
} 

那麼,你需要釋放它,然後將其設置爲NULL。否則,你已經失去了地址。