c语言中清理双链表Trie结构
我想防止内存泄漏,所以我想释放trie。 下面您可以看到我试图释放已使用的内存c语言中清理双链表Trie结构,c,trie,C,Trie,我想防止内存泄漏,所以我想释放trie。 下面您可以看到我试图释放已使用的内存 // 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;
// 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;
};
这是一个双路或四路链表,我不知道该怎么办
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;
}
但它似乎工作不正常。它给出了一个错误:
双重自由或损坏(fasttop):0x0000000000fffa70***
我似乎没有得到什么,因为当“child”和“next”都为“NULL”时,“a”是最外面的节点。我相信只有一个递归if语句可以到达这些最外围的节点之一
我将尝试将trie形象化:
[root]
|
\/
[h] -- > [b]
| |
\/ \/
[i] [y] --> [e]
所以trie包含hi、by和be。根指向第一个单词的第一个字符,所有箭头都是双链接的。从“h”到“b”是下一个,从“h”到“i”是孩子
有人能看出我做错了什么吗?非常感谢。我认为您在几个地方检查
NULL
太复杂了。当您有多个递归时,在进入函数后检查NULL
比在调用函数之前更容易
此外,如果通过指向cleaner()
的指针传递局部变量,则可以避免全局teller\u cleanup
变量
您应该只释放父元素一次,自上而下或自下而上,而不是两种方式-如果您使用调试器单步执行代码,您将注意到在
a=a->parent之后已经删除的子元素;[…]如果(a->next!=NULL).
请注意,点
和箭头->
运算符绑定非常紧密,在传统的C编码样式中,它们周围不应该有空格。嗯,它比我的实现做得更好,但由于某些原因,我仍然存在内存泄漏。谢谢出纳员的清理,我没想到。
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;
}