typedef struct Model
{
int recordId;
char *name;
}Model;
typedef struct ModelArray
{
//keeps the size that the array was initially create with. When more elements are needed
//we use this to add that many more elements
int originalSize;
//total number of elements that can be used
int elements;
//total number of elements used
int count;
//the actual array is stored here
Model *source;
}ModelArray;
void initModelArray(ModelArray *array, int numberOfElements)
{
array->originalSize = numberOfElements;
array->elements = numberOfElements;
array->count = 0;
array->source = malloc(sizeof(Model)*numberOfElements);//0 bytes in 3 blocks are definitely lost in loss record 1 of 65
}
void deallocModelArray(ModelArray *array)
{
if(array == NULL)
return;
array->elements = 0;
array->count = 0;
free(array->source);
array->source = NULL;
free(array);
}
main(int argc, const char * argv[])
{
ModelArray *models = malloc(sizeof(ModelArray));
initModelArray(models, 10);
deallocModelArray(models);
}
丢失了什么?代码对我来说看起来不错。我确信我可以先说 array->source = NULL 但不需要,对吧?
最佳答案
要正确释放这些结构,您需要按顺序执行以下操作:
free(models->source);
free(models);
如果您执行其他操作,就会泄漏内存。
编辑:
好的,看到 Model 结构后,您可能泄漏了名称,或者至少 valgrind 认为您这样做了,因为您释放了 ModelArray 结构,该结构包含指向 Model 结构的指针,该结构包含您不知道的 char*首先不要释放。
所以:
int i;
for( i=0; i<models->originalSize; i++ ) {
if( models->source[i]->name != NULL ) {
free( models->source[i]->name );
}
}
free(models->source);
free(models);
在首先分配 models->source 时,最好使用 calloc() 而不是 malloc()。这会将所有 name 指针设置为 0。如果没有这个,如果 name 碰巧包含一些垃圾,上面对 models->source[i]->name 为非 NULL 的测试可能会失败(因为使用未初始化的内存会产生未定义的行为。)
关于c - valgrind 正确吗?内存丢失了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6414773/