c - 如何用双指针释放C中的树结构

标签 c algorithm data-structures malloc valgrind

我正在编写一个关于用 C 语言构造树结构的代码,它不是二进制的。该结构包含一个水平链接、一个垂直链接和一个字符值。现在我试图释放分配来构造这棵树的每个结构,但 valgrind 给了我一个错误。我正在使用双指针指向树的头部。在函数中,pile 表示堆栈,因此我垂直堆叠每个节点,然后搜索水平节点。我将树及其结构和 valgrind 结果的示例作为图片。你能帮我理解哪里出了问题吗,因为我不明白?谢谢 !

void libererArbre(cellule ** tete)
{
    cellule * cour = * tete;
    cellule ** temp = &cour; 
    pile_t * pile;
    pile = initialisationPile(TAILLE_PILE);
    int fin = 0;    
    while(fin == 0)
    {   
        while(cour != NULL)
        {
            empiler(cour, pile);
            //printf("empilimi %c\n", cour->valeur);
            cour = cour->lienVertical;
        }
        if(!estVidePile(pile))
        {
            cour = depiler(pile);
            //printf("depilimi %c\n", cour->valeur);
            temp = &cour;
            free(temp);
            cour = cour->lienHorizontal;    
        }
        else
        {
            fin = 1;
            printf("a futet ne fin 1 apo jo \n");
        }
    }
    libererPile(pile);
}

这是 valgrind 结果的图片:

enter image description here

这是结构说明的图片:

enter image description here

最佳答案

问题出在这两行:

        temp = &cour;
        free(temp);

由于cour是局部变量,temp将指向该堆栈地址。当您调用 free(temp) 时,您正在尝试释放未使用 malloc 分配的内存地址。

你可能需要做类似的事情

        temp2 = cour;
        cour = cour->lienHorizontal;    
        free(temp);

(其中 temp2 被声明为 cellule *temp2),但如果不查看分配代码就不可能知道。

关于c - 如何用双指针释放C中的树结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56317577/

相关文章:

algorithm - 以下情况的有用数据结构

c - 通过蓝牙向提供串行端口配置文件的设备发送命令

c - 下面的内存分配有什么不同吗?

c - 在C中使用双指针插入链表

php - 哈希冲突的担忧

java - 将 Collection 和 Iterator 接口(interface)实现为内部类

java - 对于以下用例,什么可以更快地实现 trie?

c - pcap_open_live 无法打开 eth0 hexinject

c - C 实现中的浮点零(IEEE 754 不变量?)

java - 计算子图的权重