use*_*022 6 c malloc valgrind segmentation-fault circular-list
valgrind告诉我,XX块中有XX个字节,肯定会丢失记录等等
而来源是malloc,但是,我认为这是因为我没有为malloc释放足够的内存.无论如何,我提供了我认为导致堆错误的代码.
我知道我没有释放list_remove中的内存,我很确定这是问题的唯一来源.它可能需要一些临时转移,但我不知道这是否是唯一的问题.
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) {}
}
}
Run Code Online (Sandbox Code Playgroud)
list last只是给出列表的最后一个节点.
编辑:我很抱歉没有提供足够的信息,Kerrek SB,alk.这是代码的其余部分,因为你可以看到malloc出现在newnode中,我可以在那里开始创建新列表.结构很简单,有一个值和一个prev,下一个:
#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));
}
}
Run Code Online (Sandbox Code Playgroud)
请帮忙!它仍然在堆中给我一个内存泄漏错误...