这是释放整个链表的代码
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()
- 您需要一个临时节点来保存当前节点
- 让当前节点等于下一个节点
- 使用临时节点释放当前节点
如果我的任何理论听起来是错误的,请解释!
谢谢!