为什么 Valgrind 认为这段内存是 "definitely lost"?

Why does Valgrind think that this memory is "definitely lost"?

Valgrind 报告纹理 *tex 确实丢失了。但是我将这个指针保存在 mtl->tex 中以便稍后释放它。以下是来自 valgrind 的详细信息:

==17191== 4 bytes in 1 blocks are definitely lost in loss record 1 of 1 ==17191== at 0x4C2ABD0: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so) ==17191== by 0x4005FA: assignTex (test.c:30) ==17191== by 0x400689: main (test.c:47)

这是代码(MCVE):

#include <stdlib.h>
#include <string.h>

typedef struct Tex {
    int a;
} Tex;

typedef struct MTL {
    char *textureFilename;
    struct Tex *tex;
} MTL;

void freeMtl(MTL *mtl) {
    if(!mtl) return;

    if(mtl->tex) free(mtl->tex);
    free(mtl);
}

void doStuff(Tex *tex) {
    tex->a = 5;
}

char err_is_error_set() {
    return 0;
}

void assignTex(MTL *mtl) {
    if(strlen(mtl->textureFilename) != 0) {
        Tex *tex = (Tex*)malloc(sizeof(Tex));
        memset(tex, 0, sizeof(Tex));

        doStuff(tex);
        if(err_is_error_set()) {
            return;
        }

        mtl->tex = tex;
    }
}

int main(int argc, char **argv) {
    MTL *mtl = (MTL*)malloc(sizeof(MTL));
    memset(mtl, 0, sizeof(MTL));
    mtl->textureFilename = "Test";

    assignTex(mtl);
    assignTex(mtl);

    freeMtl(mtl);

    return 0;
}

为什么肯定丢了?

例如,如果发生错误,则由于此代码存在内存泄漏

    bmp_load_bitmap(bmp, mtl->textureFilename, 1/*flip vertically*/);
    if(err_is_error_set()) {
        return 0;
    }

bmp 未被释放。

同样的情况也出现在这段代码中

    tex_create_texture(tex);
    if(err_is_error_set()) {
        return 0;
    }

而且检查内存分配是否成功会更安全

如果程序完成后给定指针未被释放,Valgrind 会给出 "definitely lost" 消息。在我的例子中,错误是稍后在代码中 tex 被分配了新值并且先前的值泄漏(assignTex(mtl)调用了两次)。