free()
의 두 가지 방법으로 연결된 목록 구조의 메모리가 malloc()
인데요. 다음 C 코드로 단일 링크 된 목록을 만들었다 고 가정합니다.C에서 연결된 목록 구조 Freeing에서의 혼란
Q1) 위의 잘못된/올바른 코드와 같이 메모리 할당 해제의 세 가지 방법 중 :
#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);
}
지금, 나는 다음과 같은 질문이 있습니다.
Q2) 메모리 할당 해제를 위해 방법 1과 2에서 사용 된 것처럼 임의의 순서로 따라야합니다 (임의로 free()
도 메모리가 좋습니까?
3 개의 노드가있는 경우에만 작동합니다.이 작업을 수행하는 데 어떤 종류의 루프가 필요할 것입니다 아니? – Justin
그리고 예수님의 이름으로 불쌍한'malloc()'의 반환 가치를 버리지 마라! –
@ 카렙 아니, 그렇지 않아. 나는 C와 데이터 구조가 처음이다. 연결된 목록 DS를 구현하려고했지만 무료 사용이 확실하지 않았습니다. 그러므로 질문. – Abhinav