【发布时间】:2012-08-02 11:23:58
【问题描述】:
我一直在实施一个链表来消除我的开发技能的锈迹,但注意到在我删除中间元素的测试期间,valgrind 报告了大小为 4 的 Invalid read。
==1197== Invalid read of size 4 ==1197== at 0x804885C: main (list.c:135) ==1197== Address 0x426e76c is 4 bytes inside a block of size 12 free'd ==1197== at 0x40257ED: free (vg_replace_malloc.c:366) ==1197== by 0x804875E: list_remove (list.c:112) ==1197== by 0x8048857: main (list.c:137)
main中触发这个的代码是:
for (iter = l2->head; iter; iter = iter->next) { if (iter->n >= 10 && iter->n <= 14) list_remove(l2, iter);
删除函数是:
void list_remove(struct list *list, struct node *node)
{
if (node == list->head && node == list->tail) {
list->head = list->tail = NULL;
}
else if (node == list->head) {
list->head = node->next;
list->head->prev = NULL;
}
else if (node == list->tail) {
list->tail = node->prev;
list->tail = NULL;
}
else {
struct node *prev, *next;
prev = node->prev;
next = node->next;
prev->next = next;
next->prev = prev;
}
free(node);
}
知道我做错了什么吗?
【问题讨论】:
标签: c algorithm data-structures doubly-linked-list