内存泄漏(自由功能不起作用)

时间:2012-10-25 07:26:15

标签: c memory-leaks pthreads malloc free

使用以下代码我面临内存泄漏问题

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 OS。

2 个答案:

答案 0 :(得分:0)

您没有显示分配实际数组的位置,只显示指定指针数组的位置。因此,您很可能在未显示的代码中的其他位置发生泄漏。

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

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

答案 1 :(得分:0)

基于在评论中挖掘更多信息的答案。

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

此外,如果您有某些分配模式,则malloc保留的内存可能无法通过将来调用malloc轻松重用。这称为内存碎片,是设计内存分配器的一个重要研究课题。

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

如果您想要准确评估泄漏的内存量,您需要使用像valgrind这样的工具,或者查看您使用的malloc是否有诊断工具来帮助您。