C - 链表 : free() function is deleting my head node; how do I use free() correctly?

标签 c pointers linked-list segmentation-fault

我需要创建一个函数来删除 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

最佳答案

请注意,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);

希望对您有所帮助。

关于C - 链表 : free() function is deleting my head node; how do I use free() correctly?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37330376/

相关文章:

c - %zd 说明符是 C11 中的可选功能吗?

c - 函数中动态分配内存的范围

c++ - 如何在 C/C++ 中将非 ASCII 字符注入(inject)字符串文字

带有链接列表的 C 程序最后崩溃

c - MPI - MPI_Recv 中的消息截断

c++ - 转换 cpp 函数以在 r 中使用

c - malloc 是否生成字符串常量?

c - 将二维数组分配给结构体对象

c - 请有人帮我解释链表吗?

java - 在 LinkedList 的索引处插入