我用两种方法在链表结构中free() malloc()'ed内存,假设我用下面的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);
}现在,我有以下问题:
Q1)上述代码中显示的三种内存释放方法中,哪一种是正确的/不正确的。
Q2)是否需要遵循方法1和2中用于内存释放的free()'ing内存中的任何顺序,或者随机free()内存也可以?
发布于 2012-05-15 02:56:09
你展示的所有方法都是正确的,你应该遵循特定的顺序,只有当一个分配的内存的指针存在于另一个分配的内存中时,你才会丢失它,如果你首先释放容器。
例如,对于分配:
int ** ipp;
ipp = malloc(sizeof(int*));
*ipp = malloc(sizeof(int));正确的free顺序为:
free(*ipp);
free(ipp);和而不是
free(ipp);
free(*ipp); // *ipp is already invalid发布于 2012-05-15 02:55:01
所有这些方法都工作得很好。您可以按您喜欢的顺序释放malloc分配的内存块。
想象一下,当您释放内存时,您分配内存的顺序必须颠倒。如果是这样的话,你永远不能在列表的中间插入或删除项目。您唯一可用的动态分配的数据结构将是下推堆栈。
发布于 2012-05-15 02:58:02
这里有一个释放链表的简单方法,从表头开始。(请注意,如果您在列表的末尾,则假设"next“为NULL。)
node * it = head;
while( NULL != it ) {
node * tmp = it;
it = it->next;
free(tmp);
}https://stackoverflow.com/questions/10589351
复制相似问题