我在空闲时间学习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: %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);
}
答案 0 :(得分:1)
你不应该消耗内存NULL
。您需要free()
这样的人free(mynode->next);
,但只有在您确定之前有malloc()
来电时才需要free(list->root);
。
在您的代码中,您需要使用list->root = NULL;
代替free(prev->next);
和prev->next = NULL;
代替{{1}}