【发布时间】:2021-04-21 19:45:59
【问题描述】:
我创建了一个结构数组。数组的每个元素最多分配 4 个数字;可以有更少的数字。最初,设置为 0。我在程序中有一些内存泄漏,我想问一下第一个:
#include <stdlib.h>
#define ELEMENTS 8
#define NUM_INT 4 //Number of digits
typedef struct sth {
int* numbers;
int how_many; //How many cells with 4 digits
} sth;
void create(sth** tab) {
*tab = realloc(*tab, ELEMENTS * sizeof(**tab));
for (int i = 0; i < ELEMENTS; i++) {
sth cell;
cell.numbers = calloc(NUM_INT, sizeof (*cell.numbers));
cell.how_many = 1;
(*tab)[i] = cell; // Put in original array.
}
(*tab)[ELEMENTS-2].numbers[0] = -1; // Don't bother about the values
(*tab)[ELEMENTS-1].numbers[0] = 1;
}
void clear(sth** arr) {
free(*arr);
*arr = NULL;
}
int main(void) {
sth* arr = NULL; // Don't need to initialise to null here.
create(&arr);
//There have been functions, but I commented them out
clear(&arr);
return 0;
}
当我运行程序时,我得到了 Valgrind:
==58759== 448 bytes in 28 blocks are definitely lost in loss record 1 of 1
==58759== at 0x4837B65: calloc (vg_replace_malloc.c:752)
==58759== by 0x1091D6: create (address_of_a_file)
==58759== by 0x10A3F4: main (address_of_a_file)
==58759==
之前我使用 realloc 代替 calloc 和 vilgrind 指示行:
sth cell;
sth cell.numbers = NULL;
cell.numbers = realloc(cell.numbers, NUM_INTS*sizeof(*cell.numbers)); //this line
正如我所写,在整个程序中都会发生内存泄漏,但我想跟踪它们的第一个来源。
对我来说,好像我已经创建了新分配的内存并且没有释放以前的内容。但是我不知道,这里问题的原因是什么,因为我在程序结束时释放了内存。
非常感谢您的建议和解释。
【问题讨论】:
-
您没有在程序结束时释放内存。 每一个对 calloc/malloc/realloc 的调用必须只与一个 free 相结合。你没有释放你用
calloc分配的那个内存。 -
所以我要为每个arr[i]准备函数?免费(arr[i])?
-
是的!!!!!!!!!!!!!!!
-
@PaulFloyd 这不是 C 标准所保证的。参见例如stackoverflow.com/a/42303040/918959
-
相反,C17 7.31.12 说“使用 size 参数等于 0 调用 realloc 是一个过时的功能。”
标签: arrays c pointers memory-management valgrind