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);
}
}