打印 C 链表会产生内存泄漏



我正在使用堆用法,这是Valgrind的替代品。当我在 main 函数中打印链表时,它会产生内存泄漏(当打印函数被注释时,一切都很好(。我试图找出问题所在,但是打印功能非常简单,要么我的堆分析器出错,要么问题非常简单,以至于我找不到它。

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;
}

您没有泄漏,使用 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)

最新更新