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

gol*_*ean 33 c malloc free linked-list

我有一个非常简单的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
   }


}
Run Code Online (Sandbox Code Playgroud)

pax*_*blo 66

通常的方法是(伪代码优先):

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.
Run Code Online (Sandbox Code Playgroud)

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

您只需要一次记住一个节点,而不是您提出的整个列表.

就您需要添加到代码中的内容而言,您可以在删除期间将其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.
}
Run Code Online (Sandbox Code Playgroud)

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


cni*_*tar 9

我使用这样的东西:

for (p = curr; NULL != p; p = next) {
    next = p->next;
    free(p);
}
Run Code Online (Sandbox Code Playgroud)