免费双向链表 [英] free of doubly linked list

查看:120
本文介绍了免费双向链表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用一个C程序中的双向链表。我越来越感到困惑释放内存。


  1. 我应该按节点释放列表节点?

  2. 或者,通过指定的头和尾节点为NULL?


解决方案

您必须遍历列表和自由的每个节点。如果只设置了头和尾指针为NULL列表中的节点仍然在堆中,你有没有指针指向他们,这是一个经典的内存泄漏。

下面是一些伪code:

 节点*电流=头;
而(电流!= NULL){
   节点*下一=电流 - >接下来,
   免费(电流);
   电流=下一个;
}
//完成

您当然可以遍历的尾巴头 - 不作任何主要区别

I am using a doubly linked list in a C program. I am getting confused about freeing the memory.

  1. Should I free the list node by node?
  2. Or, by assigning head and tail nodes to NULL?

解决方案

You have to traverse the list and free each node. If you only set the head and tail pointers to NULL the list nodes are still in the heap and you have no pointers to them and that's a classic memory leak.

Here's some pseudocode:

Node* current = head;
while( current != NULL ) {
   Node* next = current->Next;
   free( current );
   current = next;
}
// done

You could of course traverse for tail to head - doesn't make any major difference.

这篇关于免费双向链表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆