简体   繁体   English

在C中释放链表结构时的困惑

[英]Confusion in Free'ing a linked list structure in C

I am juggling with two ways of free() 'ing malloc() 'ed memory in a linked list structure. 我在用链表结构中的free() 'ing malloc() 'ed内存的两种方式来玩弄。 Suppose I create a singly linked list with the following C code; 假设我用下面的C代码创建一个单链列表;

#include<stdio.h>
#include<stdlib.h>

struct node_type{
  int data;
  struct node_type *next;
  struct node_type *prev;
}
typedef struct node_type node; 
typedef struct node_type *list; 

void main(void){
  list head,node1,tail;
  head=(list)malloc(sizeof(node));
  tail=(list)malloc(sizeof(node));
  node1=(list)malloc(sizeof(node));
  head->next=node1;tail->prev=node1;
  node1->prev=head;node1->next=tail;node1->data=1;

  /*Method-1 for memory de-allocation*/
  free(head->next->next);
  free(head->next);
  free(head);

  /*OR*/

  /*Method-2 for memory de-allocation*/
  free(tail);
  free(node1);
  free(head);

  /*OR*/

  /*Method-3 for memory de-allocation*/
  free(node1);
  free(tail);
  free(head); 
}

Now, I have the following questions: 现在,我有以下问题:

Q1) Which of the three methods of memory de-allocation shown in code above are correct/incorrect. Q1)上面代码中显示的三种内存解除分配方法中的哪一种是正确/不正确的。

Q2) Is is necessary to follow any order in the free() 'ing memory as used in Methods 1 and 2 for memory de-allocation OR randomly free() 'ing memory is also fine? Q2)是否有必要按照方法1和2中所使用的free()内存中的任何顺序进行内存解除分配,或者随机free()内存也可以吗?

All the methods you showed are correct, you should follow a specific order only when the pointer to an allocated memory exists only in another allocated memory, and you will lose it if you free the container first. 您显示的所有方法都是正确的,仅当指向已分配内存的指针仅存在于另一个已分配内存中时, 应遵循特定的顺序,并且如果先释放该容器,则会丢失它。

For example, for the allocation: 例如,对于分配:

int ** ipp;
ipp = malloc(sizeof(int*));
*ipp = malloc(sizeof(int));

The correct free order will be: 正确的free订单将是:

free(*ipp);
free(ipp);

and not : 不是

free(ipp);
free(*ipp); // *ipp is already invalid

All of these methods work fine. 所有这些方法都可以正常工作。 You can free memory blocks allocated by malloc in whatever order you like. 您可以按任意顺序释放由malloc分配的内存块。

Just imagine for a moment that the order in which you allocated memory had to be reversed when you freed it. 试想一下,释放内存时必须颠倒分配内存的顺序。 If that was so you could never insert or delete items from the middle of a list. 如果是这样,您将永远无法从列表中间插入或删除项目。 Your only available dynamically allocated data structure would be a push-down stack. 您唯一可用的动态分配的数据结构将是下推堆栈。

Here's a simple way to free a linked list, starting at the head. 这是从头开始释放链接列表的一种简单方法。 (Note, this assumes "next" will be NULL if you're at the end of the list.) (请注意,如果您位于列表的末尾,则假定“ next”将为NULL。)

node * it = head;
while( NULL != it ) {
  node * tmp = it;
  it = it->next;
  free(tmp);
}

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

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