gpt4 book ai didi

c - 链接列表和大小为 4 的无效读取

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:35:13 25 4
gpt4 key购买 nike

我一直在实现一个链表来清除我的开发技能上的锈迹,但在我删除中间元素的测试中注意到 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);
}

知道我可能做错了什么吗?

最佳答案

您正在释放循环中的值,然后取消引用它以获取其“下一个”指针。您需要一个临时值才能正确执行此操作:

    for (iter = l2->head; iter; iter = next) {
next = iter->next;
if (iter->n >= 10 && iter->n <= 14)
list_remove(l2, iter);
}

关于c - 链接列表和大小为 4 的无效读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11812202/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com