gpt4 book ai didi

c - LinkedList - 如何释放使用 malloc 分配的内存

转载 作者:太空狗 更新时间:2023-10-29 16:22:04 26 4
gpt4 key购买 nike

我有一个非常简单的 C 代码,用于构建如下所示的单链表,其中我使用 malloc 为每个节点动态分配内存。在代码的最后,我想为分配的每个节点释放内存,想知道如何去做——如果我先从头节点开始并释放它,指向后续节点的指针就会丢失,内存泄漏就会发生。

另一种方法是从头节点开始,将节点指针存储在单独的指针数组或其他东西中,遍历列表直到尾指针,同时存储节点指针,一旦到达尾节点,也将其存储到其他指针数组并开始从该数组索引向后释放,直到头节点被释放。

这是实现我想要做的事情的唯一方法吗?

如果我不想使用第二个缓冲区,我该怎么做。

#include "stdio.h"
#include "stdlib.h"

struct lnk_lst
{
int val;
struct lnk_lst * next;
};

typedef struct lnk_lst item;


main()
{
item * curr, * head;
int i,desired_value;

head = NULL;

for(i=1;i<=10;i++)
{
curr = (item *)malloc(sizeof(item));
curr->val = i;
curr->next = head;
head = curr;
}

curr = head;


while(curr) {
printf("%d\n", curr->val);
curr = curr->next;
}

//How to free the memory for the nodes in this list?
for(i=1;i<=10;i++)
{
free()//?? What logic here
}


}

最佳答案

通常的方式是with(先伪代码):

node = head              # start at the head.
while node != null: # traverse entire list.
temp = node # save node pointer.
node = node.next # advance to next.
free temp # free the saved one.
head = null # finally, mark as empty list.

基本思想是在一个单独的变量中记住要释放的节点,然后在释放它之前前进到下一个节点。

您一次只需记住一个节点,而不是您建议的整个列表。

就您需要添加到代码中的内容而言,您可以在删除期间使用 head 作为不断更新的列表头(正如它的本意)和 curr 来存储您当前正在删除的项目:

while ((curr = head) != NULL) { // set curr to head, stop if list empty.
head = head->next; // advance head to next element.
free (curr); // delete saved pointer.
}

这比上面的伪代码短一点,因为它利用了 C 的“速记”来进行某些操作。

关于c - LinkedList - 如何释放使用 malloc 分配的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7025328/

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