如何使用双指针在C语言中释放树结构

时间:2019-05-26 21:43:54

标签: c algorithm data-structures malloc valgrind

我正在编写有关用C语言构造树的代码,它不是二进制的。该结构包含水平,垂直链接和char值。现在,我试图释放分配给构造该树的每个结构,但是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结果的图片:

enter image description here

这是结构爆炸的图片:

enter image description here

1 个答案:

答案 0 :(得分:0)

问题在于这两行:

if let url = testURL {
    do {
        let contents = try String(contentsOf: url)
        print(contents)
        do {
            let doc: Document = try SwiftSoup.parse(contents)
            for item in try doc.select("script") {
                let json = try item.attr("src")
                print(json)
            }
        } catch Exception.Error(let type, let message) {
            print(message)
        } catch {
            print("error")
        }
    } catch {
        // contents could not be loaded
    }
} else {
    // the URL was bad!
}

由于 temp = &cour; free(temp); 是局部变量,因此cour将指向该堆栈地址。调用temp时,您试图释放的内存地址未分配给free(temp)

您可能需要做类似的事情

malloc

(其中 temp2 = cour; cour = cour->lienHorizontal; free(temp); 被声明为temp2),但是如果不查看您的分配代码就无法知道。

相关问题