【发布时间】:2025-11-27 15:00:01
【问题描述】:
这里是释放整个链表的代码
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()
- 您需要一个临时节点来保存当前节点
- 让当前节点等于下一个节点
- 使用临时节点释放当前节点
如果我的任何理论听起来不对,请解释!
谢谢!
【问题讨论】:
-
它的工作,假设你做了,事实上,正确地建立你的列表(看起来你可能做到了)。你的理论清单是正确的。
标签: c linked-list free