下面是释放整个链表的代码
void free_list(RecordType *list)
{
RecordType *tempNode; /* temporary Node to hold on the value of previous node */
while(list != NULL) /* as long as the listnode doesn't point to null */
{
tempNode = list; /* let tempNode be listNode in order to free the node */
list = list->next; /* let list be the next list (iteration) */
free(tempNode); /* free the node! */
}
}
我认为这段代码本身工作正常(?),但我不知道如何检查。 我只应用了理论(例如,# of frees must = to the # of mallocs)
所以这里有一些我想知道的问题......
- 这个方法行得通吗?
- 我需要 malloc tempNode 吗?
- 我在 while 循环之前初始化了 tempNode...但是在我释放之后,tempNode 仍然有效...我不太明白那部分
我使用的理论:
- # of free() == # of malloc()
- 你需要一个临时节点来存放当前节点
- 让当前节点等于下一个节点
- 使用临时节点释放当前节点
如果我的任何理论听起来有误,请解释!
谢谢!
最佳答案
Does this method work?
是的,假设列表节点都是动态分配的并且之前没有被释放
Do I need to malloc tempNode?
您不需要在 free_list
中分配任何内存,但所有列表元素必须事先动态分配。您只能在使用 malloc
(或 calloc
)分配的内存上调用 free
I initialized tempNode before while loop... but after I free, tempNode still works... I don't really get that part
调用free
将内存所有权返回给系统。它可能会选择立即重新使用此内存,也可能会在一段时间内保持不变。没有什么可以阻止您再次访问内存,但读取或写入它的结果是不确定的。
如果你想让客户端代码更难意外访问释放的内存,你可以将 free_list
更改为 NULL their pointer
void free_list(RecordType **list)
{
RecordType *tempNode;
while(*list != NULL) {
tempNode = *list;
list = tempNode->next;
free(tempNode);
}
*list = NULL;
}
如果您还想检查是否确实释放了所有内存,请考虑使用 valgrind。这将报告任何内存泄漏并标记某些类型的无效内存访问。
关于c - 如何检查 free(node) 是否有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15131863/