【发布时间】:2022-02-04 06:55:08
【问题描述】:
下面是链表的基本代码。我只是接受输入然后显示它。 我动态地提供内存并释放我认为需要释放的内存。 如果我错了,请纠正我,但 new_node 应该会自动释放,因为它来自 for 循环。 我是新手,不了解内存泄漏的确切概念,也不知道如何解决 Valgrind 显示的错误。
代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node *next;
}
node;
int main(void)
{
node *list = NULL;
int num;
for (int i = 0; i < 5; i++)
{
node *new_node;
printf("Enter a number: ");
scanf("%i", &num);
new_node = malloc(sizeof(node));
new_node->data = num;
new_node->next = list;
list = new_node;
}
//display
node *temp;
temp = list;
while(temp != NULL)
{
printf("%d\n",temp->data);
temp = temp->next;
}
free(list);
}
Valgrind 错误:
practice/ $ make linked
practice/ $ valgrind ./linked
==27973== Memcheck, a memory error detector
==27973== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==27973== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==27973== Command: ./linked
==27973==
Enter a number: 1
Enter a number: 2
Enter a number: 3
Enter a number: 4
Enter a number: 5
5
4
3
2
1
==27973==
==27973== HEAP SUMMARY:
==27973== in use at exit: 64 bytes in 4 blocks
==27973== total heap usage: 6 allocs, 2 frees, 1,104 bytes allocated
==27973==
==27973== 48 bytes in 3 blocks are indirectly lost in loss record 1 of 2
==27973== at 0x483B7F3: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==27973== by 0x4011BD: main (linked.c:20)
==27973==
==27973== 64 (16 direct, 48 indirect) bytes in 1 blocks are definitely lost in loss record 2 of 2
==27973== at 0x483B7F3: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==27973== by 0x4011BD: main (linked.c:20)
==27973==
==27973== LEAK SUMMARY:
==27973== definitely lost: 16 bytes in 1 blocks
==27973== indirectly lost: 48 bytes in 3 blocks
==27973== possibly lost: 0 bytes in 0 blocks
==27973== still reachable: 0 bytes in 0 blocks
==27973== suppressed: 0 bytes in 0 blocks
==27973==
==27973== For lists of detected and suppressed errors, rerun with: -s
==27973== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
【问题讨论】:
-
free(list)只释放list指向的single 节点。free函数不知道它指向的内存内容的上下文。您需要将对malloc的所有 调用与free调用相匹配。所以如果你给malloc打了10个电话,你需要给free打10个电话。 -
free(list)只释放列表中的第一个元素,第二个元素肯定丢失,其他元素间接丢失。您必须遍历列表以释放每个节点——注意在释放节点后不要访问下一个指针。 -
好的,现在我明白了,谢谢您的帮助。
标签: c memory memory-management memory-leaks valgrind