【问题标题】:Valgrind, Blocks Are Definitely Lost even though I free?Valgrind,即使我免费,块肯定会丢失?
【发布时间】:2021-11-02 08:39:28
【问题描述】:

小提示,请忽略使用malloc代替new和使用 我自己的容器而不是矢量等......这段代码的重点 是练习基础知识。

当我运行 Valgrind 时,我得到:

==24855== HEAP SUMMARY:
==24855==     in use at exit: 0 bytes in 2 blocks
==24855==   total heap usage: 12,999 allocs, 12,997 frees, 675,432 bytes allocated
==24855==
==24855== 0 bytes in 1 blocks are definitely lost in loss record 1 of 2
==24855==    at 0x4C29F73: malloc (vg_replace_malloc.c:309)
==24855==    by 0x4014ED: ImageTagger::GetAllSegmentsByLabel(int, int**, int**, int*) (ImageTagger.cpp:100)
==24855==    by 0x402EB6: GetAllSegmentsByLabel (library2.cpp:59)
==24855==    by 0x403A8B: OnGetAllSegmentssByLabel (main2.cpp:345)
==24855==    by 0x4033A6: parser (main2.cpp:172)
==24855==    by 0x403135: main (main2.cpp:95)
==24855==

但是分配的块在main中被释放了,有什么问题吗?这是我的代码的相关部分:

ImageTagger.cpp:

StatusType ImageTagger::GetAllSegmentsByLabel(int label, int **images, int **segments, int *numOfSegments) {
    if (label <= 0 || images == nullptr || segments == nullptr || numOfSegments == nullptr) {
        return INVALID_INPUT;
    }
    *numOfSegments = Match_Num(image_tree->root, label);
    int *imageArr = (int *) malloc(sizeof(int) * (*numOfSegments));
    if (imageArr == nullptr) {
        return ALLOCATION_ERROR;
    }
    int *segArr = (int *) malloc(sizeof(int) * (*numOfSegments));
    if (segArr == nullptr) {
        free(imageArr);
        return ALLOCATION_ERROR;
    }
    int counter = 0;
    InorderTraversal(image_tree->root, imageArr, segArr, &counter, (*numOfSegments), label);
    *images = imageArr;
    *segments = segArr;
    if ((*numOfSegments) == 0) {
        *images = *segments = nullptr;
    }
    return SUCCESS;
}

main2.cpp 我有(注意最后的两条空闲线,它是怎么丢失的?):

static errorType OnGetAllSegmentssByLabel(void* DS, const char* const command) {
    int courseID, numOfLabels;
    int *images, *segments;
    ValidateRead(sscanf(command, "%d", &courseID), 1, "%s failed.\n", commandStr[GETALLSEGMENTSSBYLABEL_CMD]);
    StatusType res = GetAllSegmentsByLabel(DS, courseID, &images, &segments, &numOfLabels);

    free(images);
    free(segments);

    return error_free;
}

【问题讨论】:

    标签: c++ memory memory-leaks valgrind free


    【解决方案1】:

    如果(*numOfSegments) == 0GetAllSegmentsByLabel 中为真,会发生什么情况?

    在这种情况下,您仍然分配了 2 个 0 字节块并且它们丢失了,因为您在 if 语句中退出函数之前将两个指针都设置为 nullptr

    必须释放包括malloc(0) 在内的每个malloc。

    【讨论】:

    • 消毒剂也是 Valgrind 的一个很好的替代品 - -fsanitize=leak,address-fsanitize=memory(仅限 clang)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-22
    相关资源
    最近更新 更多