valgrind对吗?记忆力丢失了吗?

joe*_*els -1 c valgrind

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);
}
Run Code Online (Sandbox Code Playgroud)

失去了什么?代码看起来很好.我敢肯定我可以先说array-> source = NULL但不需要它,对吧?

Ori*_*ach 7

要正确释放这些结构,您需要按以下顺序执行以下操作:

free(models->source);
free(models);
Run Code Online (Sandbox Code Playgroud)

如果你做任何其他事情,你就会泄漏记忆.

编辑:

好的,看过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);
Run Code Online (Sandbox Code Playgroud)

并且在首先分配models-> source时使用calloc()而不是malloc()是个好主意.这会将所有的名称指针设置为0.如果没有这个,如果name碰巧包含一些垃圾,那么上面的模型 - > source [i] - > name的测试可能会失败(因为使用未初始化的内存会产生未定义的行为.)