【问题标题】:linked list and an Invalid read of size 4链表和大小为 4 的无效读取
【发布时间】: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


    【解决方案1】:

    嗯...您所要做的就是阅读 valgrind 消息。

    • 此处阅读无效:main (list.c:135) - 那是 iter-&gt;next
    • 从一个释放的位置,内存在此处释放:list_remove (list.c:112),即free(node);

    在移除前缓存下一个指针。

    【讨论】:

    • 谢谢。我不明白到底发生了什么,因为第 135 行至少有 2 次读取。
    • 所以?添加一些跟踪消息,你会看到。
    【解决方案2】:

    当您free(node) 时,您正在释放iter 指针。然后你尝试从不再存在的iter-&gt;next 读取。

    【讨论】:

    • 感谢 Bitmask,非常有帮助 :)
    【解决方案3】:

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

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

    【讨论】:

    • 谢谢 tbert,这很有帮助! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多