1

I am writing code to get the blood type for each generation. And it has a function, which frees the person and his ancestors, but I got those two errors: free(): double free detected in tcache 2; Aborted (core dumped). Below is the code to free the family. Any suggestion would be greatly appreciated!

void free_family(person *p)
{
    // Handle base case: input of NULL
    for (int i = 0; i < 2; i++)
    {
        // do not free NULL pointer
        if (p == NULL)
        {
            continue;
        }
        person *cursor = p -> parents[i];
        person *tmp = cursor;
        while (cursor != NULL)
        {
            //Free parents
            cursor = cursor -> parents[i];
            free(tmp);
            tmp = cursor;
        }
        // Free child
        free(cursor);
        free(p);
    }
}
jxh
  • 69,070
  • 8
  • 110
  • 193
Snowyaya
  • 23
  • 1
  • 1
  • 4
  • Somewhat unrelated, but your code should return and not enter the for loop if p is NULL. – Jeff Holt Jan 09 '21 at 02:32
  • One thing that doesn't make sense is the call `free(cursor)` after the loop. The loop only exits when `cursor` is `NULL`, so this call is equivalent to `free(NULL)`, which doesn't make sense. – Tom Karzes Jan 09 '21 at 02:35

1 Answers1

3

I haven't checked all your code, however:

Your loop iterates twice. Each time, it calls free(p) which doesn't change between iterations.

A possible fix may be to move the call to be outside of the loop.

jxh
  • 69,070
  • 8
  • 110
  • 193