【问题标题】:Why do I get free(): double free detected in tcache 2 and aborted (core dumped)*为什么我得到 free(): double free 在 tcache 2 中检测到并中止(核心转储)*
【发布时间】:2021-01-09 02:28:01
【问题描述】:

我正在编写代码来获取每一代的血型。它有一个功能,可以释放这个人和他的祖先,但我得到了这两个错误: free(): 在 tcache 2 中检测到双重空闲; 中止(核心转储)。 以下是释放家庭的代码。任何建议将不胜感激!

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

【问题讨论】:

  • 有点不相关,但如果 p 为 NULL,您的代码应该返回并且不进入 for 循环。
  • 没有意义的一件事是在循环之后调用free(cursor)。循环只在cursorNULL时才退出,所以这个调用等价于free(NULL),没有意义。

标签: c coredump double-free


【解决方案1】:

不过,我还没有检查你的所有代码:

您的循环迭代两次。每次,它都会调用free(p),这在迭代之间不会改变。

一种可能的解决方法是将调用移到循环之外。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-25
    • 2020-01-22
    • 2021-05-04
    • 1970-01-01
    • 2021-03-11
    • 2020-12-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多