-
free()ing a list
consider two functions for free()ing a linked list:
Code:
void freelist(struct node *root)
{
struct node *index, *save;
if (root != NULL)
for (index=root; index!=NULL; index=save)
{
save=index->next;
free(index);
}
}
second:
Code:
void freelist(struct node **root)
{
struct node *save;
if (*root != NULL)
for ( ; *root != NULL; *root = save)
{
save = (*root)->next;
free(*root);
}
}
when i call the first function to free the list and then try to print it i get something like:
Code:
134518592
134518608
134518624
134518640
134518656
134518672
134518688
134518704
134518720
what's that? the memory addresses of the data in the nodes? but they were freed already.
when trying to printf the list after the call to the second freelist function, i simply get 'Empty List'.
So, why is the output different? which function should i use, or are they both ok?
-
>why is the output different?
Because the first function doesn't end up setting root to null, the second does. Your print function no doubt tests for a null list and prints an appropriate message if the root is null.
>which function should i use, or are they both ok?
They're both fine for releasing the memory in a list, but you should consider what happens if you try to use the root after calling freelist. A good idea would be to have a list structure rather than just a simple node as your list so that you can maintain a consistent state without having to rely on pointers to pointers, like so:
Code:
struct list {
struct node *root;
/* Other handy stuff */
};
Then you can define freelist like this:
Code:
void
freelist(
struct list *list
)
{
if (list && list->root) {
struct node *index, *save;
for (index = list->root; !index; index = save) {
save = index->next;
free(index);
}
list->root = NULL;
/* Reset other handy stuff */
}
}
-
i see, it's like having a special structure to hold info about the list, not the list itself, cool.
here:
Code:
if (!list && !list->root) {
you meant
Code:
if (list && list->root) {
right?
thanks Prelude :) .
-
>you meant
Yes, I did. Thank you. That's the result of writing the function my way originally and then hastily changing it to mirror how you wrote it. ;)