【问题标题】:memory leak (free function not working)内存泄漏(免费功能不起作用)
【发布时间】:2012-10-15 08:13:59
【问题描述】:

我遇到以下代码的内存泄漏问题

static char **edits1(char *word)
{
    int next_idx;
    char **array = malloc(edits1_rows(word) * sizeof (char *));
    if (!array)
        return NULL;

    next_idx = deletion(word, array, 0);
    next_idx += transposition(word, array, next_idx);
    next_idx += alteration(word, array, next_idx);
    insertion(word, array, next_idx);

    return array;
}

static void array_cleanup(char **array, int rows) {

        int i;

        for (i = 0; i < rows; i++)
            free(array[i]);
}

static char *correct(char *word,int *count) {

        char **e1, **e2, *e1_word, *e2_word, *res_word = word;
        int e1_rows, e2_rows,max_size;

        e1_rows = edits1_rows(word);
        if (e1_rows) {
            e1 = edits1(word);
        *count=(*count)*300;
            e1_word = max(e1, e1_rows,*count);

            if (e1_word) {

                array_cleanup(e1, e1_rows);
                        free(e1);
                return e1_word;

            }
        }

    *count=(*count)/300;

    if((*count>5000)||(strlen(word)<=4))
        return res_word;

        e2 = known_edits2(e1, e1_rows, &e2_rows);
        if (e2_rows) {
        *count=(*count)*3000;
            e2_word = max(e2, e2_rows,*count);
            if (e2_word)
                    res_word = e2_word;
        }

        array_cleanup(e1, e1_rows);
        array_cleanup(e2, e2_rows);

        free(e1);
        free(e2);
        return res_word;
}

我不知道为什么 free() 不起作用。我在线程中调用这个函数“正确”,多个线程同时运行。我使用的是 Ubuntu 操作系统。

【问题讨论】:

  • 您的免费功能在代码中哪里不起作用?如果它在任何地方都不起作用,您是否考虑过包含 malloc.h
  • 您是否尝试过Valgrind 等工具来查找泄漏/内存问题?
  • @krammer 我没有包含 malloc.h ,它真的很重要吗?我的程序运行良好,除了内存泄漏问题
  • 这是一些奇怪的代码。为什么你(可选)乘以 300 然后除以 300?考虑#define一些常量。
  • AFAIR free() 只能释放由 *alloc() 函数分配的内存。我没有看到任何分配内存的代码...

标签: c memory-leaks pthreads malloc free


【解决方案1】:

您不会显示分配实际数组的位置,而只是显示分配指针数组的位置。所以很有可能你在你没有显示的代码的其他地方有泄漏。

此外,array_cleanup 会泄漏,因为它只会删除那些您没有显示分配位置的数组。它不会删除指针数组本身。该函数的最后一行应该是free(array);

您的主要问题是您使用了一种模糊的分配算法。相反,allocate true dynamic 2D arrays

【讨论】:

  • char **array = malloc(edits1_rows(word) * sizeof (char *));我正在使用上面的代码分配数组
  • @user1768256 在这一行中,您分配了一个指针数组,而没有分配任何实际的数据 .正如我所指出的,你错误地释放它,这就是你有内存泄漏的原因。
【解决方案2】:

答案基于在 cmets 中挖掘更多信息。

大多数 malloc 实现通常不会将内存返回给操作系统,而是保留它以供将来调用 malloc。这样做是因为将内存返回给操作系统会对性能产生很大影响。

此外,如果您有特定的分配模式,那么 malloc 保留的内存可能不容易被以后调用 malloc 重用。这称为内存碎片,是设计内存分配器的一大研究课题。

无论 htop/top/ps 报告的内容不是您当前使用 malloc 在程序中分配了多少内存,而是所有库所做的所有各种分配、它们的储备等,这可能比您分配的要多得多.

如果您想准确评估泄漏了多少内存,则需要使用 valgrind 之类的工具,或者查看您使用的 malloc 是否有诊断工具来帮助您。

【讨论】:

    猜你喜欢
    • 2011-06-23
    • 1970-01-01
    • 2019-07-29
    • 1970-01-01
    • 1970-01-01
    • 2011-02-14
    • 2022-08-14
    相关资源
    最近更新 更多