我正在使用Heapusage(替代Valgrind)。当我在主要功能中打印链接列表时,它会导致内存泄漏(在对打印功能进行注释时,就可以了)。我试图找出问题所在,但是打印功能是如此简单,以至于我的堆分析器出现了问题,或者问题如此简单,以至于我找不到它。
typedef struct Point {
int x, y;
struct Point *next;
} Point;
Point *NewPoint(const int x, const int y, Point *head) {
Point *point = (Point *)malloc(sizeof(Point));
point->next = NULL;
point->x = x;
point->y = y;
if (head == NULL) {
head = point;
} else {
Point *current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = point;
}
return head;
}
void FreeList(Point *head) {
Point *current = head;
while (current != NULL) {
Point *tmp = current;
current = current->next;
free(tmp);
}
}
void PrintList(Point *head) {
while (head) {
printf("[%d, %d]\n", head->x, head->y);
head = head->next;
}
}
int main() {
Point *head = NULL;
head = NewPoint(2, 3, head);
PrintList(head);
FreeList(head);
return 0;
}
答案 0 :(得分:3)
您没有泄漏,已通过valgrind-3.14.0.GIT测试
==13568== Memcheck, a memory error detector
==13568== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==13568== Using Valgrind-3.14.0.GIT and LibVEX; rerun with -h for copyright info
==13568== Command: ./a.out
==13568== [2, 3]
==13568==
==13568== HEAP SUMMARY:
==13568== in use at exit: 0 bytes in 0 blocks
==13568== total heap usage: 2 allocs, 2 frees, 1,040 bytes allocated
==13568==
==13568== All heap blocks were freed -- no leaks are possible
==13568==
==13568== For counts of detected and suppressed errors, rerun with: -v
==13568== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)