Mike
Mike

Reputation: 1

Linked-list in c error - free(): invalid pointer error OR segmentation fault

I'm creating a linked-list in c and cannot add another node after the 4th. When I use free(node), I get the error: free(): invalid pointer Aborted (core dumped) If I remove the free(node) declaration, however, I get a segmentation fault. I'm assuming this is some sort of memory issue, but I can't locate the source of the problem.

Structures used:

struct node
{
    int id;
    struct process * p;
    struct node * next;
};

struct queue
{
    struct node * head;
    struct node * tail;
};

Enqueue function that is supposed to add a node to the list:

void enqueue(struct queue * q, struct node * newNode)
{
    if(q->tail == NULL)
    {
        q->head = q->tail = newNode;
        return;
    }

    q->tail = q->tail->next = newNode;

    // free statement useful?
    free(newNode);
}

Upvotes: 0

Views: 491

Answers (1)

Ctx
Ctx

Reputation: 18410

The free statement is indeed not useful.

In this statement:

q->tail = q->tail->next = newNode;

you assign the pointer newnode to two pointer variables. But in the next statement

free(newNode);

you render this pointer invalid, so dereferencing (or freeing) the pointers stored in q->tail and the next pointer of the second-last element of your list results in undefined behaviour.

Solution is to not free the pointer while a valid reference to it exists in the process.

Upvotes: 3

Related Questions