我一直在实现一个链接列表来消除我的开发技能的锈迹,但注意到在我删除中间元素的测试期间,valgrind 报告了大小为 4 的无效读取。
==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)
触发此操作的主要代码是:
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);
}
知道我可能做错了什么吗?