【发布时间】: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