recursive function for freeing memory

Viewed 474

I'm trying to write a recursive function that frees up the entire linked list. I'm still quite new to recursive functions so I'm not sure if I'm even doing this right. I ran valgrind to my code and I got back an error but I'm not sure how to interpret it.

==1156== 16 bytes in 1 blocks are indirectly lost in loss record 1 of 3
==1156==    at 0x4C2FB0F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==1156==    by 0x422454: main (destroy.c:24)

I believe the error lies somewhere in my code. Any help would be really nice. Here is my code:

#include <stdio.h>
#include <stdlib.h>

typedef struct node
{
    int number;
    struct node* next;
}
node;

void destroy(node* list);

int main (void)
{
    node* list = NULL;
    node* n = malloc(sizeof(node));
    if (n == NULL)
    {
        return 1;
    }
    n->number = 1;
    n->next = NULL;
    list = n;
    n = malloc(sizeof(node));
    if (n == NULL)
    {
        return 1;
    }
    n->number = 2;
    n->next = NULL;
    list->next = n;
    n = malloc(sizeof(node));
    if (n == NULL)
    {
        return 1;
    }
    n->number = 3;
    n->next = NULL;
    list->next->next = n;

    destroy(list);
}

void destroy(node* list)
{
    if(list->next == NULL)
    {
        free(list);
    }
    else
    {
        return destroy(list->next);
    }
}
1 Answers

You are only free'ing just one node that's at the end of the list. Because the "nodes" are not freed when the recursion unwinds.

You'd to rewrite it like:

void destroy(node* list)
{
    if (list == NULL) return;
    destroy(list->next);
    free(list);
}

But IMO, recursion isn't necessary here. A simple loop might be a better choice:

void destroy(node* list)
{
    node* temp;

    while (list != NULL) {
        temp = list;
        list = list->next;
        free(temp);
    }
}

Think of 1000's of nodes in the list. Why do you want "save" the nodes in the call stack for no good reason? It's both inefficient and dangerous (call stack could overflow).

Related