首页 > 解决方案 > 在 C 中运行 Valgrind 时,我收到大小为 8 的无效读取

问题描述

我编写了一个 C 链表程序,并且正在运行一个简单的测试工具,以确保所有功能都以最佳方式工作。然而,尽管没有内存泄漏,但根据 Valgrind 的说法,我的代码有两个问题,这些是

头文件:LinkedList.h

typedef struct LinkedListNode
{
    void* data;
    struct LinkedListNode* next;
    struct LinkedListNode* previous;
} LinkedListNode;

typedef struct
{
    LinkedListNode* head;
    LinkedListNode* tail;
    int size;
} LinkedList;

linkedlist.c 中的 removeStart 函数

void* removeStart(LinkedList* list)
{
    LinkedListNode* curr = list->head;

    void* ptr;

    if (curr->next == NULL)
    {
        free(curr);
        list->head = NULL;
    }
    if (curr->next != NULL)    //This is where the Invalid read of size 8 error occured
    {
        ptr = curr -> data;

        list -> head = curr -> next;

        free(curr);
        curr = NULL;

        list -> head -> previous = NULL;
        list->size--;
    }
 
 
    return ptr;
}

removeLast 函数

void* removeLast(LinkedList* list)
{
    LinkedListNode* curr = list -> head;
    LinkedListNode* secondLast;

    void* ptr;

    if (isEmpty(list) == 0)
    {
        printf("List is empty");
    }
    else
    {
        while (curr->next != NULL)
        {
            secondLast = curr;
            curr = curr->next;
        }

        if (curr == list->head)
        {
            list -> head = NULL;
        }

    }

    ptr = curr->data;
    list->size--;
    list -> tail = secondLast;
    secondLast->next = NULL;        //This is where Use of uninitialised value of size 8 occured

    free(curr);
    curr = NULL;
    return ptr;
}

标签: cvalgrind

解决方案


removeStartif curr->next == NULLthen you free curr 但在 2 行之后再次使用它。

如果removeLast列表为空,则secondLast永远不会设置。


推荐阅读