0

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.

4
  • 1
    You have forgotten to write a base case. Commented Dec 8, 2024 at 11:37
  • 1
    When should you stop calling ft_treeclear? You never do that. Commented Dec 8, 2024 at 11:40
  • 1
    There's also no null-pointer checks. Which would be good to have to know when to not call ft_treeclear. Commented Dec 8, 2024 at 11:41
  • 3
    Recursuin is infinite if there is always a recursive call in the control flow. Whether some data structure is the same or different from some other data structure is irrelevant. Commented Dec 8, 2024 at 12:01

1 Answer 1

3

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.