在c中清理双链表Trie结构

时间:2016-03-17 14:17:05

标签: c trie

我想防止内存泄漏,所以我想释放trie。 下面你可以看到我试图释放使用的内存。

value = cursor.getString(fieldIndex);

它是一个双向或四向链接列表,不确定我用它来调用它。

// to see how many words are cleaned up.
static int teller_cleanup = 0;

struct ac {
    int value;
    char character; 
    char * word;
    struct ac *next;
    struct ac *previous;
    struct ac *child;
    struct ac *parent;
};

但它似乎无法正常工作。它给出了一个错误:

双重免费或损坏(fasttop):0x0000000000fffa70 ***

我似乎没有得到,因为'child'和'next'都是'NULL'而'a'是最外层的节点。而且我相信只有一个重复的if语句可以转到其中一个大的节点。

我将试图想象出这个特里:

void cleaner(struct ac* a) {
    ac * temp = NULL;
    if (a != NULL) {
        if (a -> child == NULL && a -> next == NULL) {
            teller_cleanup ++;
            if (a -> parent != NULL) {
                temp = a -> parent;
            }
            else {
                temp = a -> previous;
             }
             free(a -> word);
             free(a);
             a = temp;
        }
        if (a -> child != NULL) {
            cleaner(a -> child);
        }
        if (a -> next != NULL) {
            cleaner(a -> next);
        }
     }
 }

int cleanup(struct ac* a) {
    // means that it is in the root
    // therfore it needs to go to the first node.
    if (a -> next == NULL && a -> parent == NULL) {
        a = a -> child;
    }
    cleaner(a);
    return teller_cleanup;
}

所以trie包含单词hi,by和be。根指向第一个单词的第一个字符,所有箭头都是双重链接。从'h'到'b'是下一个,从'h'到'i'是孩子。

有人可能会看到我做错了吗?非常感谢。

1 个答案:

答案 0 :(得分:2)

我认为你在几个地方检查NULL会让它变得太复杂。当你有多次递归时,在输入函数后检查NULL会更容易,而不是在调用它之前。

此外,如果通过指针将局部变量传递给teller_cleanup,则可以避免使用全局cleaner()变量。

void cleaner(struct ac *a, int *teller_cleanup) 
{
    if (a != NULL) {
        cleaner(a->next, teller_cleanup);
        cleaner(a->child, teller_cleanup);
        free(a->word);
        free(a);
        (*teller_cleanup)++;
    }
}

int cleanup(struct ac *a)
{
    int teller_cleanup = 0;
    cleaner(a, &teller_cleanup);
    return teller_cleanup;
}
相关问题