Search code examples
ccoredumpdouble-free

Why do I get free(): double free detected in tcache 2 and aborted (core dumped)*


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

Solution

  • 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.