Ania
Ania

Reputation: 450

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?

Upvotes: 3

Views: 72

Answers (4)

Sumeet
Sumeet

Reputation: 8292

The linked list is a data structure that is unlike array group of non-contiguous memory locations. This is the reason you have to traverse the entire linked list. Had it been an array, you would just need a pointer to the first element, and call free on it and that's it, because in arrays it's contiguous memory locations.

Upvotes: 1

Jonathan Leffler
Jonathan Leffler

Reputation: 753615

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

Upvotes: 2

Vlad from Moscow
Vlad from Moscow

Reputation: 310950

You need to free all the allocated memory for nodes of the list.

If to support that the list is declared something like

struct pomiar *head = NULL;

Then the function can look for example the following way.

void free_list( struct pomiar **head )
{
    while ( *head )
    {
        struct pomiar *tmp = *head;
        *head = ( *head )->nast;
        free( tmp );
    }
}

and called like

free_list( &head );

In this case the original head will be equal to NULL after exiting the function and can be used anew as an empty list.

Upvotes: 1

machine_1
machine_1

Reputation: 4454

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

Upvotes: 1

Related Questions