【发布时间】:2020-12-04 20:59:40
【问题描述】:
我像这样使用 valgrind 运行我的程序:
valgrind --leak-check=full ./a.out < in0.txt > out0.txt
并得到以下输出:
==13077== Memcheck, a memory error detector
==13077== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==13077== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==13077== Command: ./a.out
==13077==
==13077== Conditional jump or move depends on uninitialised value(s)
==13077== at 0x40491F: OnGetMostViewedClasses (in /home/user/a.out)
==13077== by 0x404498: parser (in /home/user/a.out)
==13077== by 0x404263: main (in /home/user/a.out)
==13077==
==13077==
==13077== HEAP SUMMARY:
==13077== in use at exit: 0 bytes in 0 blocks
==13077== total heap usage: 90 allocs, 90 frees, 6,200 bytes allocated
==13077==
==13077== All heap blocks were freed -- no leaks are possible
==13077==
==13077== For counts of detected and suppressed errors, rerun with: -v
==13077== Use --track-origins=yes to see where uninitialised values come from
==13077== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
-bash-4.2$
虽然它指的是这里使用的StatusType res;:
static errorType OnGetMostViewedClasses(void* DS, const char* const command) {
int numOfClasses;
int *courses = NULL, *classes = NULL;
StatusType res;
ValidateRead(sscanf(command, "%d", &numOfClasses), 1, "%s failed.\n", commandStr[GETMOSTVIEWEDCLASSES_CMD]);
if (numOfClasses > 0) {
courses = (int *)malloc(numOfClasses * sizeof(int));
classes = (int *)malloc(numOfClasses * sizeof(int));
if (courses == NULL || classes == NULL) {
res = ALLOCATION_ERROR;
}
}
if (res != ALLOCATION_ERROR) {
res = GetMostViewedClasses(DS, numOfClasses, courses, classes);
}
if (res != SUCCESS) {
printf("%s: %s\n", commandStr[GETMOSTVIEWEDCLASSES_CMD], ReturnValToStr(res));
if (courses != NULL) free(courses);
if (classes != NULL) free(classes);
return error_free;
}
printf("%s: %s\n", commandStr[GETMOSTVIEWEDCLASSES_CMD], ReturnValToStr(res));
printf("Course\t|\tClass\n");
for (int i = 0; i < numOfClasses; i++)
{
printf("%d\t|\t%d\n", courses[i], classes[i]);
}
printf("--End of most viewed classes--\n");
if (courses != NULL) free(courses);
if (classes != NULL) free(classes);
return error_free;
}
并声明如下:
typedef enum {
SUCCESS = 0,
FAILURE = -1,
ALLOCATION_ERROR = -2,
INVALID_INPUT = -3
} StatusType;
所以我的问题是,我怎样才能解决这个问题不更改上面的代码,因为它是给我们的,我的教授告诉我:“你不被允许更改它”和“valgrind 发现的任何错误都会给你一个 0 的标记”?
欢迎任何想法或建议。
请注意:除了这个问题,我有 0 个内存泄漏问题(根据我测试的 32 个输入文件)
【问题讨论】:
-
你能在启用调试信息的情况下编译这段代码吗(对于 g++,这是 -g 标志),所以 valgrind 可以告诉我们它在抱怨哪一行?这里没有显示任何行号。我们可能还需要查看调用函数(
parser)来回答这个问题。即,DS 和 command 是否指向已初始化的内存? -
"DS 和命令指向初始化内存?"是的,我很确定,我一开始就用 g++ 编译了它(这里发布的那个没有 g++),valgrind 向我展示了以下行“StatusType res;”
标签: c++ enums memory-leaks initialization valgrind