memory leak (free function does not work)

advertisements

I am facing memory leak problem with the below code

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

I don’t know why free() is not working. I am calling this function "correct" in thread, multiple threads are running simultaneously.I am using Ubuntu OS.


You don't show where you allocate the actual arrays, you just show where you allocate the array of pointers. So it is quite possible that you have leaks elsewhere in the code you are not showing.

Furthermore, array_cleanup leaks since it only deletes those arrays you don't show where you allocate. It doesn't delete the array of pointers itself. The final row of that function should have been free(array);.

Your main problem is that you are using an obscure allocation algorithm. Instead, allocate true dynamic 2D arrays.