【问题标题】:C LinkedList - how to free memory?C LinkedList - 如何释放内存?
【发布时间】:2015-09-13 17:31:53
【问题描述】:

我想写一个小函数来释放链表的内存。已使用 malloc 创建节点。

一个典型的函数是:

void freeList(struct node* head)
{
struct node* tmp;

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

}

我的问题是我收到以下错误,我不知道如何解决它们:

警告:来自不兼容指针类型的赋值 tmp = l;

错误:“linked_list”没有名为“next”的成员 l = l -> next;

声明如下:

struct node_s {
struct node_s *next;
char msg[MAX_MSG_LEN];
unsigned int time;
};

typedef struct node_s node;

struct linked_list_s {
node *head;
};

typedef struct linked_list_s linked_list;

void list_free(linked_list *l) {
   struct node *tmp;
   while (l !=NULL) {
     tmp = l;
     l = l -> next;
     free(tmp);
  }
}

【问题讨论】:

    标签: c memory linked-list malloc


    【解决方案1】:

    您需要将l->head 分配给list_free() 函数内的tmp 变量,并在free() tmp 时使用另一个变量来存储下一个节点,就像这样

    void list_free(linked_list *l) 
     {
       struct node *tmp;
       struct node *next;
       if (l == NULL)
          return;
       tmp = l->head;
       while (tmp != NULL) 
        {
          next = tmp->next;          
          free(tmp);
          tmp = next;
        }
     }
    

    【讨论】:

    • 我放弃了。我会选择你的解决方案,而不是随机投票。
    • 嘿,我是新来的。但它适用于迈克尔。谢谢你的帮助!你是我的英雄!继续!
    • @Tom,如果它对您有用,您可以接受答案,您是否使用调试器检查所有内存是否已释放?
    猜你喜欢
    • 2011-10-24
    • 2020-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-25
    • 2011-01-31
    相关资源
    最近更新 更多