Valgrind告诉我有XX个内存块丢失,总共XX字节,记录了blablabla。
而且源代码中使用了malloc函数,但我认为这是因为我没有为malloc函数释放足够的内存。无论如何,我提供了我认为导致堆错误的代码。
我意识到在list_remove函数中我没有释放内存,我非常确定这是问题的唯一来源。可能需要对temp进行一些移位,但我不知道是否只有这个问题。
list_t *list_remove(list_t *list, list_t *node) {
list_t *oldnode = node;
node->prev->next = node->next;
node->next->prev = node->prev;
if (list != oldnode) {
free(oldnode);
return list;
} else {
list_t *value = list->next == list ? NULL : list->next;
free(oldnode);
return value;
}
}
void list_free(list_t *list) {
if (list) {
while (list_remove(list, list_last(list)) != NULL) {}
}
}
list_last简单地返回列表的最后一个节点。
编辑:对不起,我没有提供足够的信息,Kerrek SB,alk。这是代码的其余部分,你可以看到malloc在newnode中发生,在那里我可以开始创建新的列表。结构很简单,有一个值和一个prev、next:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "ll.h"
struct list {
char *value;
struct list *next;
struct list *prev;
};
const char *list_node_value(list_t *node) {
return node->value;
}
list_t *list_first(list_t *list) {
return list;
}
list_t *list_last(list_t *list) {
return list->prev;
}
list_t *list_next(list_t *node) {
return node->next;
}
list_t *list_previous(list_t *node) {
return node->prev;
}
static void failed_allocation(void) {
fprintf(stderr, "Out of memory.\n");
abort();
}
static list_t *new_node(const char *value) {
list_t *node = malloc(sizeof(list_t));
if (!node) failed_allocation();
node->value = malloc(strlen(value)+1);
if (!node->value) failed_allocation();
strcpy(node->value, value);
return node;
}
list_t *list_insert_before(list_t *list, list_t *node, const char *value) {
list_t *insert_node = new_node(value);
insert_node->prev = node->prev;
insert_node->next = node;
insert_node->next->prev = insert_node;
insert_node->prev->next = insert_node;
if (list == node) {
return insert_node;
} else {
return list;
}
}
list_t *list_append(list_t *list, const char *value) {
if (list) {
(void) list_insert_before(list, list, value);
return list;
} else {
list_t *node = new_node(value);
node->prev = node->next = node;
return node;
}
}
list_t *list_prepend(list_t *list, const char *value) {
if (list) {
return list_insert_before(list, list, value);
} else {
list_t *node = new_node(value);
node->prev = node->next = node;
return node;
}
}
list_t *list_remove(list_t *list, list_t *node) {
list_t *oldnode = node;
node->prev->next = node->next;
node->next->prev = node->prev;
if (list != oldnode) {
free(oldnode);
return list;
} else {
list_t *value = list->next == list ? NULL : list->next;
free(oldnode);
return value;
}
}
void list_free(list_t *list) {
if (list) {
while (list_remove(list, list_last(list)) != NULL) {}
}
}
void list_foreach(list_t *list, void (*function)(const char*)) {
if (list) {
list_t *cur = list_first(list);
do {
function(cur->value);
cur = cur->next;
} while (cur != list_first(list));
}
}
请帮忙!在堆中仍然出现了内存泄漏错误...
free
对应一个malloc
。由于你的代码中没有malloc
,因此无法确定问题出在哪里。 - Kerrek SB