在链表中创建新节点时,Leak_DefinitelyLost警告(C)



我有一个程序,在其中我使用了一个链表,并且我还有一个名为NewNode的函数,它是通过main或其他函数(甚至是递归函数(调用的。

这个程序非常慢,所以我用Valgrind检查了一下,除了这个功能之外,似乎一切都很好,因为我在malloc上得到了Leak_DefinitelyLost错误,泄漏了大约1000字节(所以必须解决(。我想我需要以某种方式释放节点,但我真的不明白如何释放。

以下是如何定义节点以及如何定义函数:

#include <stdlib.h>
#include <string.h>
typedef struct node{
char* data;
struct node* next;
}list;
struct node* NewNode(char* to_insert) {
struct node *new = malloc(sizeof(*new));
new->data = malloc(strlen(to_insert) + 1);
strcpy(new->data, to_insert);
new->next = NULL;
return new;
}

编辑:我有两个功能要释放,一个释放所有列表,一个只从列表中删除特定节点,它们是:

void Free_All(struct node* head){
if (head == NULL)
return;
Free_All(head->next);
free(head->data);
free(head);
}
struct node* Delete_node(struct node* head, char* to_delete){
struct node *p, *dummy;
p = head;
if (p != NULL && strcmp(p->data,to_delete) == 0) {
head = p->next;
return head;
}
while (p)
{
dummy = p->next;
if (dummy != NULL){
if (strcmp(dummy->data, to_delete) == 0){
dummy = p->next;
p->next = dummy->next;
//free(dummy);
break;
}
}
if (p->next == NULL){
break;
}
p = p->next;
}
return head;
}

注意:如果我试图取消注释free,我会得到一个SIGSEGV错误,程序就会中断。

至少显示的函数Delete_node会产生内存泄漏,因为删除的节点没有用存储的字符串释放。

struct node* Delete_node(struct node* head, char* to_delete){
struct node *p, *dummy;
p = head;
if (p != NULL && p->data == to_delete) {
head = p->next;
return head;
}
//...

注意,它似乎不是这个比较

p->data == to_delete

您必须使用标准函数strcmp

if ( p != NULL && strcmp( p->data, to_delete ) == 0 ) {

使用您的方法,该功能可以按以下方式显示

struct node* Delete_node(struct node* head, const char* to_delete)
{
if ( head != NULL )
{
if ( strcmp( head->data, to_delete ) == 0 ) 
{
struct node *tmp = head;
head = tmp->next;
free( tmp->data );
free( tmp );
}
else
{
struct node *p = head;
while ( p->next != NULL && strcmp( p->next->data, to_delete ) != 0 )
{
p = p->next;
}
if ( p->next != NULL )
{
struct node *tmp = p->next;
p->next = tmp->next;
free( tmp->data );
free( tmp );
}
}
}
return head;
}

最新更新