[英]why I got memory still reachable when it's not reachable
this is the struct of list:这是列表的结构:
struct link {
char name[20];
list* next;
};
this is the function that valgrind say that the memory is still reachable.这是 valgrind 说 memory 仍然可以访问的 function。
list* make_new_link(char* name) {
list* new_link = (list*)malloc(sizeof(list));
new_link->name = name;
new_link->next = NULL;
return new_link;
}
at the end of the code I freed the list like so: NOTE: list* lst is the pointer of the list在代码的末尾,我像这样释放了列表: 注意:list* lst 是列表的指针
void free_list(list* lst) {
list* temp = NULL;
while(lst->next != NULL) {
temp = lst;
lst = lst->next;
free(temp);
}
}
so why I still get an memory problem?那么为什么我仍然遇到 memory 问题?
You never clean up the first element because of while(lst->next != NULL)
.由于
while(lst->next != NULL)
,您永远不会清理第一个元素。 Fix it like this:像这样修复它:
void free_list(list* lst) {
list* temp = NULL;
while(lst != NULL) {
temp = lst;
lst = lst->next;
free(temp);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.