C内存泄漏以释放链表



当我valgrind时,我的main.c中有内存泄漏和错误(错误在另一个测试文件中(。(最后的屏幕(此外,我必须在list.c中的函数list_destroy中释放
查看:

编辑:感谢@kirjosiepo,我删除了下面create_cell函数中的malloc!现在:valgrind_updated

cell.c

// cell_s has gpointer ptr_value and struct cell_s *next
cell_t* create_cell(gpointer v) {
cell_t *c = malloc(sizeof(cell_t));
c->next = NULL;
c->ptr_value = v;
return c;
}
void destroy_int(gpointer data) {
free((int *) data);
}

list.c

// list_s has cell_t *head and int size
list_t* list_create() {
list_t *l = malloc(sizeof(list_t));
l->head = NULL;
l->size = 0;
return l;
}
void list_insert_in_head(list_t *l, gpointer element) {
// typedef cell_t* adr
adr address_c = create_cell(element);
address_c->next = l->head;
l->head = address_c;
++l->size;
}
void list_insert_next(list_t *l, gpointer element, adr address) {
adr address_c = create_cell(element);
if (l->head == NULL) {
liste_insert_in_head(l, element);
} else {
address_c->next = address->next;
address->next = address_c;
}
++l->size;
} 
void list_remove_in_head(list_t *l) {
if (l->head != NULL) {
l->head = l->head->next;
}
--l->size;
}
void list_remove_after(list_t *l, adr address) {
if (l->head->next == NULL) {
printf("Use list_remove_in_head functionn");
} else if (address != NULL) {
address->next = address->next->next;
--l->size;
}
}
// Here is the problem !
void list_destroy(list_t *l, list_gfree ft_destroy) {
adr current = l->head;
while(current != NULL) {
adr tmp = current;
current = current->next;

ft_destroy(tmp->ptr_value);
tmp->ptr_value = NULL;

ft_destroy(tmp);
}
free(l);
}

main.c

int main(void) {
list_t *l = list_create();
int *ptr_int = (int *)malloc(sizeof(int));
*ptr_int = 4;
list_insert_in_head(l, ptr_int);
printf("Size : %dn", l->size);
int *ptr_int_2 = (int *)malloc(sizeof(int));
*ptr_int_2 = 7;
list_insert_in_head(l, ptr_int_2);
printf("Size : %dn", l->size);
int *ptr_int_3 = (int *)malloc(sizeof(int));
*ptr_int_3 = 100;
list_insert_next(l, ptr_int_3, l->head);
printf("Size : %dn", l->size);
list_remove_in_head(l);
printf("Size : %dn", l->size);
list_remove_next(l, l->head);
printf("Size : %dn", l->size);
list_remove_next(l, l->size);
printf("Size : %dn", l->size);
list_destroy(l, destroy_int);
}

valgrind
在我的插入中检测到内存泄漏。valgrind

感谢您帮助我处理0个内存泄漏和0个错误!:-(

我还没有测试这是否真的是(唯一的(问题,但有一个代码是这样的:

create_cell(gpointer v) {
// clip
c->ptr_value = malloc(sizeof(int));
c->ptr_value = v;

进行分配,然后丢弃指针。

让我们继续!还能找到什么?

list_remove_in_head()中,单元l->head被重写而不被释放。它可以用这样的东西来修复:

void list_remove_in_head(list_t *l) {
if (l->head != NULL) {
void *tmp = l->head->next;
free(l->head->ptr_value);
free(l->head);
l->head = tmp;
}
--l->size;
}

list_remove_after()也是如此,但我想你可以自己解决。:(

最新更新