나는 자유 시간에 C를 배우고있다. C#, Java 및 Python에 익숙합니다. 연습으로 C에서 링크드리스트를 작성했습니다. 올바르게 기능하고 에러 처리 등을합니다.링크 된 목록 제거 후 메모리 해제
그러나 메모리 누수 문제를 해결하려고합니다. 나는 C가 자동 가비지 수집을 가지고 있지 않다는 것을 알고있다. 그렇다면 목록을 삭제 한 후 어떻게 목록의 구성원을 "무료"로 할 수 있습니까? removeAllList()라는 함수를 작성했습니다. 이 함수는 목록에서 구성원을 성공적으로 제거하지만 해당 구성원의 메모리가 여전히 할당되어 있음을 알고 있습니다. 무료 ([myArgument]) 함수를 사용하여 시도했지만 무한 루프가 발생합니다. free() 함수를 사용하여 코드에서 제거 된 멤버의 메모리를 성공적으로 할당 해제 할 위치를 표시 할 수 있습니까?
#include<stdio.h>
#include<stdlib.h>
struct Member{
int data;
struct Member *next;
};
struct List{
int size;
struct Member *root;
};
struct Member *createMember(int i){
struct Member *new;
new = malloc(sizeof(struct Member));
new->data = i;
new->next = NULL;
return new;
}
struct List *createList(int i){
struct List *new;
new = malloc(sizeof(struct List));
new->root = createMember(i);
new->size = 1;
return new;
}
void printList(struct List *list){
struct Member *current = list->root;
//error handling for empty list
if(list->size < 1){
printf("Error: List is empty");
}
//if list is not empty
else{
printf("List size: %i\nContents: ", list->size);
while(current->next != NULL){
printf("%i, ", current->data);
current = current->next;
}
printf("%i\n", current->data);
}
}
void addList(struct List *list, int i){
struct Member *current = list->root;
while(current->next != NULL){
current = current->next;
}
current->next = createMember(i);
list->size++;
}
void removeAllList(struct List *list, int i){
struct Member *current = list->root;
struct Member *prev = list->root;
if(list->size < 1){
//list is empty, end function now
return;
}
//remove all matching list head
while(current->data == i){
if(list->size <= 1){
list->root = NULL;
list->size--;
//list is empty, end function now
return;
}
else{
list->root = current->next;
current = list->root;
list->size--;
}
}
current = current->next;
//remove all matching list body
while(current->next != NULL && list->size > 1){
if(current->data == i){
prev->next = current->next;
list->size--;
}
prev = current;
current = current->next;
}
//remove all matching list tail
if(current->data == i && list->size > 1){
prev->next = NULL;
list->size--;
}
}
main(){
struct List *myList;
myList = createList(4);
addList(myList, 12);
addList(myList, 9);
addList(myList, 4);
addList(myList, 43);
addList(myList, 4);
printList(myList);
removeAllList(myList, 4);
printList(myList);
}
의
free(prev->next);
를 사용할 필요는'사람 3 free' 및 정보'남자 malloc'를 시도? – kdopen