简体   繁体   English

没有双向链表

[英]free of doubly linked list

I am using a doubly linked list in a C program. 我在C程序中使用双向链表。 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? 还是通过将头和尾节点分配为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. 如果仅将头和尾指针设置为NULL,则列表节点仍在堆中,并且没有指向它们的指针,这是经典的内存泄漏。

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. 您当然可以从头到尾遍历-没什么大不同。

If they were dynamically allocated, you need to free the nodes. 如果它们是动态分配的,则需要释放节点。 Keep in mind that if your nodes hold pointers to some data, and that data was also dynamically allocated, you'll need to free that too. 请记住,如果您的节点持有指向某些数据的指针,并且该数据也是动态分配的,那么您也需要释放它们。

Something like: 就像是:

list_node* node = head;
while (node)
{
    /* depends */
    /* free(node->data); */

    list_node* next = node->next;
    free(node);
    node = next;
}

You have to free each node. 您必须释放每个节点。 If you just set the head and tail nodes to NULL, you will leak all of the memory allocated for the list. 如果仅将头节点和尾节点设置为NULL,则将泄漏为该列表分配的所有内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM