crecursioncompiler-errorsbinary-tree

gcc complains for infinite recursion while freeing binary tree


I am trying to write a generic free function for a binary tree.

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;
}

As I have to use the compiler flags -Wextra -Werror -Wall, the compiler complains about infinite recursion:

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

Why is this warning generated? tree->left and tree->right are not the same as tree, so the compiler cannot be sure that the recursion is infinite.


Solution

  • You need to add base case like:

    void    ft_treeclear(t_tree **tree, void (*del)(void*))
    {
        if (!tree || !(*tree)) // Base case: Stop recursion if tree is NULL or empty
            return;