【问题标题】:How to free a tree structure in C with a double pointer如何在 C 中使用双指针释放树结构
【发布时间】:2019-05-26 21:43:54
【问题描述】:

我正在编写一个关于用 C 语言构建树结构的代码,它不是二进制的。该结构包含一个水平链接、一个垂直链接和一个字符值。现在我正在尝试释放分配给构建这棵树的每个结构,但是 valgrind 给了我一个错误。我正在使用双指针指向树的头部。在函数中,堆意味着堆栈,所以我垂直堆叠每个节点,然后搜索水平节点。我将树及其结构和 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 的结果图片:

下面是结构说明图:

【问题讨论】:

  • 如果不查看创建树的代码,我们将无法为您提供帮助。您似乎有一个指向堆栈上变量的指针,而不是分配的变量。这可能是树的根——或者它可能是另一个节点。如果我不得不猜测,很可能你没有分配根节点。

标签: c algorithm data-structures malloc valgrind


【解决方案1】:

问题在于这两行:

        temp = &cour;
        free(temp);

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

你可能需要做类似的事情

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-24
    • 1970-01-01
    • 2020-04-15
    • 2017-07-27
    • 2021-08-07
    • 2016-04-01
    • 2021-07-30
    相关资源
    最近更新 更多