我已经实现了一个链接列表来消除我的开发技能中的锈迹,但是注意到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);
}
你知道我会做错什么吗?
最佳答案
您正在释放循环中的值,然后取消对它的引用以获取其“下一个”指针您需要一个temp值才能正确执行此操作:
for (iter = l2->head; iter; iter = next) {
next = iter->next;
if (iter->n >= 10 && iter->n <= 14)
list_remove(l2, iter);
}