在 C 结构中使用 free() 的正确方法是什么

What is the correct way of use free() in C structure

我对 C 中的结构和自由操作有点困惑。 我必须使用这个结构(我知道定义 *tList 而不是 tList 不是最好的主意,但它必须是那样)

    typedef struct cel{
    int elto;
    struct cel *bif;
    struct cel *next;
} *tList;

bif 指向 previus 元素,所以你不要 free() 因为我认为它没有必要

MalloctList list=(tList)malloc(sizeof(struct cel));

稍后我需要释放内存。我不知道哪种方式是正确的

用列表调用 limpiar

 void limpiar (tList  borrar)
{
    tList aux;
    tList aBorrar;

    for(aBorrar = borrar; aBorrar != NULL; aBorrar = aux)
    {
        aux=aBorrar->next;
        free(aBorrar);
    }  
    return;
}

使用 &list 调用 limpiar

void limpiar (tList  * borrar)
    {
        tList aux;
        tList aBorrar;

        for(aBorrar = *borrar; aBorrar != NULL; aBorrar = aux)
        {
            aux=aBorrar->next;
            free(aBorrar);
        }  
        return;
    }

如果通过引用传递列表(第二个选项),您将能够清除调用者数据中指向列表的指针,或至少清除其中之一。虽然这不是绝对必要的,也不是一个完美的解决方案,但它是一种很好的编程风格,可以减少在 free 之后引用单元格或调用 free 两次的可能性。函数应该这样修改:

void limpiar(tList *borrar)
{
    tList aux;
    tList aBorrar;

    for (aBorrar = *borrar; aBorrar != NULL; aBorrar = aux) {
        aux = aBorrar->next;
        free(aBorrar);
    }
    *borrar = NULL;
}

在调用者中,您可以这样调用 limpiar

limpiar(&list);
// list is NULL now.