Reputation: 3
I want to write a small function that shall free the memory of a linked list. The nodes have been created with malloc.
A typical function for this is:
void freeList(struct node* head)
{
struct node* tmp;
while (head != NULL)
{
tmp = head;
head = head->next;
free(tmp);
}
}
My problem is that I receive the following errors and i dont know how to fix them:
warning: assignment from incompatible pointer type tmp = l;
error: 'linked_list' has no member named 'next' l = l -> next;
The declarations are given:
struct node_s {
struct node_s *next;
char msg[MAX_MSG_LEN];
unsigned int time;
};
typedef struct node_s node;
struct linked_list_s {
node *head;
};
typedef struct linked_list_s linked_list;
void list_free(linked_list *l) {
struct node *tmp;
while (l !=NULL) {
tmp = l;
l = l -> next;
free(tmp);
}
}
Upvotes: 0
Views: 1111
Reputation: 53046
You need to assign l->head
to the tmp
variable inside list_free()
function and have another variable to store the next node while you free()
tmp
, like this
void list_free(linked_list *l)
{
struct node *tmp;
struct node *next;
if (l == NULL)
return;
tmp = l->head;
while (tmp != NULL)
{
next = tmp->next;
free(tmp);
tmp = next;
}
}
Upvotes: 1