我正在尝试为二叉树编写一个通用的自由函数。
typedef struct s_tree
{
void *content;
struct s_tree *left;
struct s_tree *right;
} t_tree;
void ft_treeclear(t_tree **tree, void (*del)(void*))
{
ft_treeclear(&((*tree)->left), del);
ft_treeclear(&((*tree)->right), del);
del((*tree)->content);
free((*tree));
*tree = NULL;
}
由于我必须使用编译器标志 -Wextra -Werror -Wall,编译器抱怨无限递归:
gcc -Wextra -Werror -Wall -c -o obj/main.o code/main.c -Ilibft -Ihead
gcc -Wextra -Werror -Wall -c -o obj/parse_tree.o code/parse_tree.c -Ilibft -Ihead
code/parse_tree.c: In function ‘ft_treeclear’:
code/parse_tree.c:128:9: error: infinite recursion detected [-Werror=infinite-recursion]
128 | void ft_treeclear(t_tree **tree, void (*del)(void*))
| ^~~~~~~~~~~~
code/parse_tree.c:130:9: note: recursive call
130 | ft_treeclear(&((*tree)->left), del);
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
cc1: all warnings being treated as errors
make: *** [Makefile:34: obj/parse_tree.o] Error 1
为什么会产生这个警告? tree->left 和tree->right 与tree 不同,因此编译器无法确定递归是无限的。
您需要添加基本案例,例如:
void ft_treeclear(t_tree **tree, void (*del)(void*))
{
if (!tree || !(*tree)) // Base case: Stop recursion if tree is NULL or empty
return;