Zegna
Zegna

Reputation: 23

free(temp) frees the rear of my queue. How do I free it

Ok so I have a function to print a queue. I use a temp Node to iterate through the linked list. When I try to free the temporary node, it also frees the rear of my queue (the last node inside the queue)

struct QNode *temp = q->front;

printf("Queue: %d", temp->value);
while (temp->next != NULL)
{
    temp = temp->next;
    printf(" -> %d", temp->value);
}
printf("\n");

free(temp);

I have a very long algorithm and If i dont free the temp I will have hundreds of thousands of trash memory. And I cant afford it

Upvotes: 1

Views: 62

Answers (2)

4386427
4386427

Reputation: 44274

It seems to me that you have misunderstood what free(temp) is doing.

free(temp) will not free temp Instead it will free the node that temp points to.

After your loop, temp points to the last node in your list so calling free(temp) will free the last node. Your linked list will be broken because the node before the last node now points to a free'ed object.

Misunderstanding number two seems to be that temp needs to be free'ed. It doesn't.

temp is an object with automatic storage duration (aka a local variable). It will be destroyed automatically when the function returns.

Like:

void printList(...)
{
    struct QNode *temp = q->front;  // temp is just a local variable

    printf("Queue: %d", temp->value);
    while (temp->next != NULL)
    {
        temp = temp->next;
        printf(" -> %d", temp->value);
    }
    printf("\n");

    // free(temp);   Don't call free on temp
    //               temp will be automatically destroyed once the function completes
}

Upvotes: 0

David Ranieri
David Ranieri

Reputation: 41017

The rule is one free per malloc, since you are not allocating space for your temporary node (is just a pointer to the front), you dont have to call free, just ignore it.

Upvotes: 2

Related Questions