释放内存的递归函数
recursive function for freeing memory
我正在尝试编写一个递归函数来释放整个链表。我对递归函数还是很陌生,所以我不确定我是否做对了。我 运行 对我的代码进行了 valgrind,但返回了一个错误,但我不确定如何解释它。
==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)
我认为错误出在我的代码中。任何帮助都会非常好。这是我的代码:
#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);
}
}
您只释放了列表末尾的一个节点。因为当递归展开时 "nodes" 没有被释放。
你可以像这样重写它:
void destroy(node* list)
{
if (list == NULL) return;
destroy(list->next);
free(list);
}
但是 IMO,这里不需要递归。一个简单的循环可能是更好的选择:
void destroy(node* list)
{
node* temp;
while (list != NULL) {
temp = list;
list = list->next;
free(temp);
}
}
想想列表中的 1000 个节点。为什么你无缘无故想要 "save" call stack 中的节点?它既低效又危险(调用堆栈可能溢出)。
我正在尝试编写一个递归函数来释放整个链表。我对递归函数还是很陌生,所以我不确定我是否做对了。我 运行 对我的代码进行了 valgrind,但返回了一个错误,但我不确定如何解释它。
==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)
我认为错误出在我的代码中。任何帮助都会非常好。这是我的代码:
#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);
}
}
您只释放了列表末尾的一个节点。因为当递归展开时 "nodes" 没有被释放。
你可以像这样重写它:
void destroy(node* list)
{
if (list == NULL) return;
destroy(list->next);
free(list);
}
但是 IMO,这里不需要递归。一个简单的循环可能是更好的选择:
void destroy(node* list)
{
node* temp;
while (list != NULL) {
temp = list;
list = list->next;
free(temp);
}
}
想想列表中的 1000 个节点。为什么你无缘无故想要 "save" call stack 中的节点?它既低效又危险(调用堆栈可能溢出)。