【问题标题】:C - Linked lists: free() function is deleting my head node; how do I use free() correctly?C - 链表:free() 函数正在删除我的头节点;如何正确使用 free()?
【发布时间】:2016-05-19 17:36:14
【问题描述】:

我需要创建一个函数来删除 c 中链表的前 n 个节点并返回删除的节点数。如果列表小于 n,它应该为空。 另外,我不能使用递归。

使用现在的代码,它可以工作,但我没有释放“已删除”节点的内存。如果我取消注释应该释放内存的部分,我会在 codeboard.io 上收到此错误:

Input: 5 + [ 61 62 63 64 65 66 ]
Output: expected 5 + [ 66 ]
        obtained 5 + [19333664 ]

那个随机数似乎是它正在访问内存中的“垃圾”。 如何正确释放不再使用的节点?

listas.h 中的代码:

typedef struct lligada {
    int valor;
    struct lligada *prox;
} *LInt;

LInt newLInt (int, LInt);

int drop (int, LInt *);

listas.c 中的代码

#include <stdlib.h>
#include "listas.h"

int drop (int n, LInt *l){
    int count = 0;
    LInt *aux;
    while(n>0 && (*l)!=NULL){
          n--;
          count++;
          //aux = &((*l));
          *l = (*l)->prox;
          //free(*aux);
    }
return count;
}

练习代码板链接:https://codeboard.io/projects/16259

【问题讨论】:

  • 我在写我的答案时忽略了l 是一个双指针的事实。对此感到抱歉。一般来说,建议使用普通指针而不是多级指针。
  • 好的,知道了。我想我现在明白了!
  • 强烈建议:不要通过“typedef”隐藏“指针”。而是使用 typedef 给结构一个“短”名称,然后在声明结构的实例时,将其设为指针。
  • 为了便于阅读和理解:变量名应该有意义,('l' 和 'n' 没有意义)变量名应该指示内容或用法(或更好,两者兼而有之)。跨度>
  • drop() 函数内这一行:LInt *aux; 应该导致编译器输出警告消息。因为变量aux 既没有设置也没有使用。编译时,始终启用所有警告,然后修复这些警告。 (对于gcc,至少使用:-Wall -Wextra -pedantic 我也使用:-Wconversion -std=gnu99

标签: c pointers linked-list segmentation-fault


【解决方案1】:

注意LInt 被定义为一个指向struct lligada指针。因此,drop 函数的l 参数是一个指向struct lligada 的指针的指针。让我们调用l 指向list_headLInt 变量。

所以,这行:

aux = &((*l));

实际上分配给aux的是list_head的地址,而不是list_head指向的struct lligada

因此,解决方案是将aux 定义为LInt,然后执行:

aux = *l;
*l = (*l)->prox;
free(aux);

希望对您有所帮助。

【讨论】:

    【解决方案2】:

    通过不使 aux 成为双指针,我达到了与 jboockmann 类似的解决方案,但正如我在他的解决方案中所说,我不明白这是什么错误以及为什么错误。

    int drop (int n, LInt *l){
        int count = 0;
        LInt aux;
        while(n>0 && (*l)!=NULL){
              n--;
              count++;
              aux = *l;
              *l = (*l)->prox;
              free(aux);
            }
        return count;
    }
    

    【讨论】:

      猜你喜欢
      • 2015-06-09
      • 1970-01-01
      • 2014-04-02
      • 1970-01-01
      • 2018-11-15
      • 2018-09-04
      • 2020-08-25
      • 1970-01-01
      相关资源
      最近更新 更多