Где мне поместить free () в C? - PullRequest
1 голос
/ 28 мая 2020

Я немного новичок в C -программировании и не могу понять, где мне освободить массив int *, который я инициализировал. Я попытался поставить free(array) после того, как получил то, что мне нужно, но Valgrind все еще сообщает об утечке памяти и недействительном свободном месте в предложенном мной месте. Где я должен поместить вызов free(array) в этом коде?

Примечание: реальная реализация кода удалена, чтобы упростить код с сохранением ошибки.

// C-language code (C99)
#include <stdio.h>
#include <stdlib.h>

int fib(int index, int *array, int initBlocks);
int processFib(int index);
int doubleStorage(int **array, int initialBlocks);

int main() {
    int ans = processFib(10);
    printf("ans = %d", ans);
    return 0;
}

// initialises an array and calls the fib(...) function
int processFib(int index) {
    int defaultInitBlocks = 10;
    int *array = calloc(defaultInitBlocks, sizeof(int));
    array[1] = 1;
    array[2] = 1;
    int ans = fib(index, array, defaultInitBlocks);
    free(array); /* Valgrind says InvalidFree here  ----------------------*/
    return ans;
}

// doubles storage of array using realloc
int doubleStorage(int **array, int initialBlocks) {
    int factor = 2;
    int *temp = realloc(*array, factor * initialBlocks * sizeof(int));
    /* Valgrind says the realloc here is a DefinitelyLost memory leak --------*/
    if (!temp) {
        free(*array);
        return -1;
    } else {
        *array = temp;
        for (int i = initialBlocks; i < factor * initialBlocks; i++) {
            (*array)[i] = 0;
        }
        return factor * initialBlocks;
    }
}


// doubles storage if 'index' is greater than array storage. Else, returns 1
int fib(int index, int *array, int initBlocks) {
    if (index >= initBlocks) {
        int newBlocks = doubleStorage(&array, initBlocks);
        return fib(index, array, newBlocks);
    }
    return 1;
}

EDIT: SOLUTION MOVED НА ОТВЕТЫ

1 Ответ

0 голосов
/ 28 мая 2020

РЕШЕНИЕ

Двойной указатель теперь используется в функции fib (), которая сбрасывает предупреждение Valgrind (код ниже). Обращайтесь к @WhozCraig за его комментарием.

int fib(int index, int **array, int initBlocks) {
    if (index >= initBlocks) {
        int newBlocks = doubleStorage(array, initBlocks);
        return fib(index, array, newBlocks);
    }
    if (array[index] > 0) {
        return (*array)[index];
    } else {
        (*array)[index] = fib(index - 1, array, initBlocks)
                + fib(index - 2, array, initBlocks);
        return (*array)[index];
    }
}
...