c - 内存泄漏(自由函数不起作用)

标签 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 操作系统。

最佳答案

您不会显示分配实际数组的位置,而仅显示分配指针数组的位置。因此,您未显示的代码中的其他地方很可能存在泄漏。

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

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

关于c - 内存泄漏(自由函数不起作用),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13063614/

相关文章:

c - 查找整数分区的字典顺序

c - llvm优化

c - libcurl:有没有办法在不登录的情况下获取 FTPS 证书?

Android NDK 内存使用

java - 如何在无限循环中使用更少的堆空间?

c++ - 使用 pthread 和引用保护 C++ 类

c++ - 如何在 C/C++ 中创建数学曲线(可能只是图像)

c - 无限循环中的内存泄漏

c - 如何在不强制使用 c 的情况下为每个线程分配任务,即每个线程在完成第一项工作后需要执行一些工作?

使用 pthread.c 创建线程