Search code examples
cvalgrind

I'm receiving Invalid read of size 8 when running Valgrind in C


I've written a C linkedlist program and am running a simple test harness to ensure that all functions are working optimally. However, despite there being no memory leaks, according to Valgrind I'm having two issues with my code, these being

  • Invalid read of size 8
  • Use of uninitialised value of size 8 Could anybody help with this issue as I'm not sure as to what's causing the issue.

Header file: LinkedList.h

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

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

The removeStart function in linkedlist.c

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;
}

The removeLast function

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;
}

Solution

  • In removeStart if curr->next == NULLthen you free curr but use it again 2 lines down.

    In removeLast if the list is empty then secondLast is never set.