【问题标题】:How do I free a linked list in C?如何在 C 中释放链表?
【发布时间】:2013-10-27 19:04:54
【问题描述】:

在 C 语言中,我有类似的东西:

typedef struct bucket {
int value;
struct bucket *next;
} Bucket;

typedef struct table {
int size;
Bucket **buckets;
} Table;

现在我做Table *t = malloc(sizeof(Table));

还有t->buckets = calloc(10, sizeof(Bucket));

释放表 *t 是free(t);对吗?

现在,我如何才能释放存储桶链表和每个节点?

【问题讨论】:

  • 它可以编译吗? struct next *bucket 不应该是结构 bucket *bucket;
  • 抱歉应该是struct bucket *next

标签: c linked-list free nodes dynamic-memory-allocation


【解决方案1】:

您应该以对称方式为每个malloc/calloc 调用free

Table *t = malloc(sizeof(Table));
t->buckets = calloc(10, sizeof(Bucket));
...
free(t->buckets);
free(t);

如果你错过了释放t->buckets,你会泄漏内存,因为Table 结构只包含一个指向桶的指针并且不包含它们。编译器也不会为你插入它。

【讨论】:

    【解决方案2】:

    另一件可能出错的事情是释放一个节点,然后尝试访问下一个节点,因此您需要先保存下一个指针。

    Bucket *bptr, *next;
    
    bptr = *t;
    while (bptr) {
        next = bptr->next;
        free(bptr);
        bptr = next;
    } 
    free(t);
    t=NULL;
    

    【讨论】:

      猜你喜欢
      • 2020-02-01
      • 1970-01-01
      • 2016-06-22
      • 2018-06-03
      • 2011-09-19
      • 2011-05-04
      • 2021-07-07
      • 2013-10-30
      • 1970-01-01
      相关资源
      最近更新 更多