简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM