Search code examples
clistlinked-listfreesingly-linked-list

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?


Solution

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