我对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;
}
编辑:解决方案已移至答案
解决方案
现在在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];
}
}