gpt4 book ai didi

c - 从C中的链表中释放内存

转载 作者:行者123 更新时间:2023-11-30 15:16:24 31 4
gpt4 key购买 nike

我一直在尝试释放加载到链接列表中的文件的分配内存,我已设法释放节点,但我不知道如何释放文件值副本的分配内存。

我尝试过类似的事情:

void FreeString(struct node * newNode)
{
for (int i = 0; i < 5; i++)
{
free(newNode->string);
}
}

但是编译器会因段错误而崩溃,并且 valgrind 仍然会指出内存泄漏。

如果有人能告诉我我做错了什么,并指出正确的方向,我将不胜感激。

Full code:

结构:

typedef struct node
{
char *string;
struct node *next;
}node;

// main function here...

void Push(struct node **RefHead, char *word)
{
struct node *newNode = NULL;

newNode = (struct node *)malloc(sizeof(node));

newNode->string = (char*)malloc(strlen(word) + 1); // can't free this part here
strcpy(newNode->string, word);
newNode->next = *RefHead;
*RefHead = newNode;

}

将文件加载到内存中:

void FileToNode()
{
struct node *head = NULL, *current = NULL;

infile = fopen("file.txt", "r");
if (infile == NULL)
{
printf("Could not open file\n");
exit(1);
}

while (fgets(word, sizeof(word), infile))
{
Push(&head, word);
}

fclose(infile);

current = head;

while(current)
{
printf("%s", current->string);
current = current->next;
}


freeAll(head);

}

免费功能:

void freeAll(struct node *head)
{
struct node *current = NULL;

while ((current = head) != NULL)
{
head = head->next;
free(current);
}
}

最佳答案

我错过了什么吗?有什么问题:

void freeAll(struct node *head)
{
struct node *current = NULL;

while ((current = head) != NULL)
{
head = head->next;
free(current->string);
free(current);
}
}

关于c - 从C中的链表中释放内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33113510/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com