我在空闲时间学习C。我熟悉C#、Java和Python。作为练习,我在C中写了一个链表。它功能正确,有错误处理等。
然而,我正在努力修复内存泄漏。我知道C没有自动垃圾收集功能。那么,在删除列表后,我如何"释放"列表中的成员呢?我编写了一个名为removeAllList()的函数。该函数成功地从列表中删除了该成员,但我知道该成员的内存仍在分配中。我尝试过使用free([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: %inContents: ", list->size);
while(current->next != NULL){
printf("%i, ", current->data);
current = current->next;
}
printf("%in", 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);
}
您不应该制作消耗内存的东西NULL
。你需要像这样free()
:free(mynode->next);
,但前提是你确定之前有malloc()
调用。
在您的代码中,您需要使用free(list->root);
而不是list->root = NULL;
,使用free(prev->next);
而不是prev->next = NULL;