Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: removing linked list

I've got a linked list of the following structures:

struct pomiar {
    unsigned int nr_pomiaru;
    unsigned int nr_czujnika;
    char data_i_czas[20];
    double temp;
    struct pomiar *nast;
};

I'm allocating all elements with malloc(): each element is pointed at by the previous one.

While freeing the list, should I go through the whole list and free the *nast pointers till the last one or what exactly should I do?

like image 466
Ania Avatar asked Feb 23 '26 18:02

Ania


2 Answers

Yes, you should go through the list, taking a copy of the nast pointer for the current element, then freeing the current element, then making the copied nast value into the current element. You can't access the memory (reliably) after it is free — don't! Hence the copying.

void free_list(struct pomiar *list)
{
    while (list != NULL)
    {
        struct pomiar *nast = list->nast;
        free(list);
        list = nast;
    }
}
like image 74
Jonathan Leffler Avatar answered Feb 25 '26 10:02

Jonathan Leffler


Yes. In order to free the list, you must go through the entire list and free each node explicitly.

void list_free(struct pomiar *head)
{
    struct pomiar *tmp = head;
    while(head)
    {
        head = head->next;
        free(tmp);
        tmp = head;
    }
}
like image 34
machine_1 Avatar answered Feb 25 '26 08:02

machine_1