我正在编写一个关于用 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 结果的图片:
这是结构说明的图片:
最佳答案
问题出在这两行:
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/