【发布时间】:2016-02-15 22:55:05
【问题描述】:
我不知道为什么我的链表有内存泄漏。
我有一个方法叫insertAtFront()
void insertAtFront(Node **head, char *key) {
Node *new = malloc(sizeof(Node));
if (!new) fatal("Malloc of new Node failed");
new->word = key;
new->next = *head;
*head = new;
}
然后我有一个释放节点的removeAtFront() 方法。
void removeAtFront(Node **head) {
Node *newhead = (*head)->next;
free(*head);
*head = newhead;
}
如果我只添加一个节点然后删除它,就没有泄漏。如果我删除了多个节点,valgrind 会显示与添加的额外节点数量成正比的泄漏。我真的不明白为什么会在节点被释放时发生这种情况。有什么想法吗?
【问题讨论】:
-
没有足够的代码显示评论。您需要显示调用这些方法的方式/时间/地点。
-
请提供显示问题的代码minimal complete and verifiable example。从这段不完整的代码中无法判断问题所在。
-
注意:如果
*head == NULL,则不应出现Node * newhead = (*head)->next;。 -
free( *head );发生在 free'ing(*head)->word之前,需要这样做吗? -
是的,就是这样。谢谢!
标签: c memory-leaks linked-list