Reputation: 7143
I have a following sturcture for creating linked list, how can I free the allocated memeory?
typedef struct linked_list {
struct linkedl_ist *number;
POINTER house;
} list;
typedef list *LIST;
typedef void pointer
i have following list
LIST l1;
l1 = some_function(pointer);
These l1
is constructed using some variables. This is a linked list data structure as i mentioned. How can I free the memory allocated for l1
?
[EDIT]
l1
holds a memory of 8 byte.
Upvotes: 1
Views: 293
Reputation: 51029
l1
doesn't need to be freed. It's on the stack. Return from the function you're in and it will automatically go away. The way to free what l1
points to is the same as the way to free the rest of the elements of the list: walk the list (using ->number
) and free each element as you go.
LIST node = l1;
LIST next;
while (node != NULL)
{
next = node->number;
free(node);
node = next;
}
Upvotes: 3
Reputation: 55467
You have to free the memory pointers individually. There's not really a magic bullet here, you have to loop over the linked list and free the pointers for each node, then if your linked list itself is dynamically allocated, you have to free that.
It's important to free things in the correct order so you don't end up with dangling pointers. In other words, if you have pointer p which points to another pointer p2, you need to be sure to free p2 and then p. You don't want to free p before you free p2, because when you try to free p2 you are going through a dangling pointer to do it (e.g. free(p->p2) but p is already freed).
Upvotes: 2
Reputation: 22989
I think that you should free each element of your list manually, starting from l1, then l1->number etc.
Upvotes: 1