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
*nastpointers till the last one or what exactly should I do?
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;
}
}
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With