c++ - Valgrind,即使我有空, block 也肯定会丢失?

标签 c++ memory memory-leaks valgrind free

Small Note, Please Ignore the use of malloc instead of new and the use of my own containers instead of vector etc... The point of this code was to practice the basics.

当我运行 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==

但是分配的 block 在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;
}

最佳答案

如果 GetAllSegmentsByLabel 中的 (*numOfSegments) == 0 为 true,会发生什么?

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

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

关于c++ - Valgrind,即使我有空, block 也肯定会丢失?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69054502/

相关文章:

c++ - Qt 构建可以开箱即用静态链接?

c++ - 如何找出文件夹是否需要管理权限才能修改其内容?

c++ - 共享库仅绑定(bind)到不处理的库

python - 多处理全局变量内存复制

.NET 内存泄漏?

haskell io流内存

ios - 仪器:泄漏和分配 (tvOS)

c++ - 是否可以将对象实例移动到 QT 项目中不同代码点的不同线程?

c++ - 当字节顺序很重要时 - 强制转换操作

java - 使用 Eclipse 内存分析器分析堆转储