free of doubly linked list

有些话、适合烂在心里 提交于 2019-12-24 12:09:43

问题


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?

回答1:


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.




回答2:


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;
}



回答3:


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.



来源:https://stackoverflow.com/questions/1886320/free-of-doubly-linked-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!