C 循环双链表中的内存释放

C 循环双链表中的内存释放,c,segmentation-fault,malloc,valgrind,circular-list,C,Segmentation Fault,Malloc,Valgrind,Circular List,valgrind告诉我,我在XX块中有XX个字节,这些字节肯定是丢失的 源代码在malloc中,但是,我认为这是因为我没有为malloc释放足够的内存。无论如何,我已经提供了我认为导致堆错误的代码 我知道我没有释放list_remove中的内存,我很确定这是问题的唯一来源。这可能需要一些临时工,但我不知道这是否是唯一的问题 list_t *list_remove(list_t *list, list_t *node) { list_t *oldnode = node; node-

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) {}
    } 
}
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));
    }
}
#包括
#包括
#包括
#包括“ll.h”
结构列表{
字符*值;
结构列表*下一步;
结构列表*prev;
};
常量字符*列表节点值(列表节点){
返回节点->值;
}
首先列出(列出){
退货清单;
}
list_t*list_last(list_t*list){
返回列表->上一页;
}
list_t*list_next(list_t*节点){
返回节点->下一步;
}
列表*列表*上一个(列表*节点){
返回节点->上一步;
}
静态作废失败\u分配(作废){
fprintf(stderr,“内存不足”。\n”);
中止();
}
静态列表*新节点(常量字符*值){
list_t*node=malloc(sizeof(list_t));
如果(!node)分配失败_();
节点->值=malloc(strlen(值)+1);
如果(!node->value)分配失败();
strcpy(节点->值,值);
返回节点;
}
list_t*list_insert_before(list_t*list,list_t*节点,常量字符*值){
列表\u t*插入\u节点=新的\u节点(值);
插入_node->prev=node->prev;
插入_节点->下一步=节点;
插入_节点->下一步->上一步=插入_节点;
插入_节点->上一步->下一步=插入_节点;
如果(列表==节点){
返回insert_节点;
}否则{
退货清单;
}
}
list*list\U append(list*list,常量字符*值){
如果(列表){
(无效)在(列表、列表、值)之前插入列表;
退货清单;
}否则{
列表_t*节点=新_节点(值);
节点->上一个=节点->下一个=节点;
返回节点;
}
}
列表\u t*列表\u前置(列表\u t*列表,常量字符*值){
如果(列表){
返回列表\在之前插入(列表、列表、值);
}否则{
列表_t*节点=新_节点(值);
节点->上一个=节点->下一个=节点;
返回节点;
}
}
列表*列表*删除(列表*列表,列表*节点){
列表*oldnode=节点;
节点->上一个->下一个=节点->下一个;
节点->下一步->上一步=节点->上一步;
如果(列表!=旧节点){
自由(oldnode);
退货清单;
}否则{
list\u t*value=list->next==list?空:list->next;
自由(oldnode);
返回值;
}
}
无效列表(列表*列表){
如果(列表){
while(list_remove(list,list_last(list))!=NULL){
} 
}
无效列表(列表,无效(*函数)(常量字符*){
如果(列表){
list_t*cur=list_first(list);
做{
函数(cur->value);
cur=cur->next;
}while(cur!=list_first(list));
}
}
请帮忙!它仍然在堆中给我一个内存泄漏错误…

代码看起来正常


如何定义列表?
list\t
是否有任何成员引用动态分配的内存?如果是这样,您可能还需要释放这些文件引用的内存

如果您关心list_free(),我建议您在源代码处强化删除链,以下假设在所有操作完成后,您希望*list为空(因为整个列表刚刚被删除)

或者类似的。通过传递外部列表指针的地址调用:

list_t *list = NULL;

.. initialize and use your list...

// free the list
list_free(&list);

编辑在OP发布了更多代码后,有几件事情非常引人注目

  • list\u newnode()
    不设置
    prev
    next
    的值,因此它们包含垃圾
  • 这里的每个其他函数都假定(1)正确初始化了next和prev。坦白地说,我很惊讶在第二个add的开始阶段这并没有错
  • 循环列表插入必须假定插入的新节点可以是初始列表本身。看来你正在努力做这件事,比实际需要的要困难得多。请记住,循环列表可以将任何节点作为列表头,这与删除当前列表“头”时的效果一样。发生这种情况时,必须有一种机制来重新向调用者建立新的列表“头”。当删除最后一个节点时,同样的机制必须允许将列表头设置为NULL

    您的代码似乎公开尝试在不使用指向指针的指针的情况下执行此操作,但它们使循环链表的任务变得更加容易。代码中需要注意的其他事项:

    • 大多数函数似乎试图通过返回值向调用方建议列表头应该是什么。相反,他们应该通过in/out参数强制执行它
    • 任何相对于另一个节点插入新节点的函数都应返回新节点
    • list\u prepend()
      list\u append()
      函数应视为相对于列表头的核心插入函数。其他API(
      list\u insert\u before()
      list\u insert\u after()
      ,等等)应该完全与您要在其之前或之后插入的有效现有节点相关,正如我上面所说的,始终返回指向新插入节点的指针。您将看到这两个非基于根的插入器函数不再通过列表头
    • 除了在执行解引用之前没有检查无效指针之外,大多数实用程序函数都是正确的。仍然有一些没有,但至少现在是可控的

    list_t *list = NULL; .. initialize and use your list... // free the list list_free(&list);

    #include <stdio.h>
    #include <stdlib.h>
    #include <memory.h>
    #include <string.h>
    #include <assert.h>
    
    // node structure
    typedef struct list_t {
        char *value;
        struct list_t *next;
        struct list_t *prev;
    } list_t;
    
    static void failed_allocation(void) {
        fprintf(stderr, "Out of memory.\n");
        abort();
    }
    
    
    // initialize a linked list header pointer. Just sets it to NULL.
    void list_init(list_t** listpp)
    {
        if (listpp)
            *listpp = NULL;
    }
    
    // return the value-field of a valid list node.
    // otherwise return NULL if node is NULL.
    const char *list_node_value(list_t *node)
    {
        return (node ? node->value : NULL);
    }
    
    // return the next pointer (which may be a self-reference)
    //  of a valid list_t pointer.
    list_t *list_next(list_t *node)
    {
        return (node ? node->next : NULL);
    }
    
    // return the previous pointer (which may be a self-reference)
    //  of a valid list_t pointer.
    list_t *list_previous(list_t *node)
    {
        return (node ? node->prev : NULL);
    }
    
    
    // return the same pointer we were passed.
    list_t *list_first(list_t *headp)
    {
        return headp;
    }
    
    // return the previous pointer (which may be a self-reference)
    //  of the given list-head pointer.
    list_t *list_last(list_t *headp)
    {
        return list_previous(headp);
    }
    
    // insert a new item at the end of the list, which means it
    //  becomes the item previous to the head pointer. this handles
    //  the case of an initially empty list, which creates the first
    //  node that is self-referencing.
    list_t *list_append(list_t **headpp, const char* value)
    {
        if (!headpp) // error. must pass the address of a list_t ptr.
            return NULL;
    
        // allocate a new node.
        list_t* p = malloc(sizeof(*p));
        if (p == NULL)
            failed_allocation();
    
        // setup duplicate value
        p->value = (value) ? strdup(value) : NULL;
    
        // insert the node into the list. note that this
        //  works even when the head pointer is an initial
        //  self-referencing node.
        if (*headpp)
        {
            (*headpp)->prev->next = p;
            p->prev = (*headpp)->prev;
            p->next  = (*headpp);
            (*headpp)->prev = p;
        }
        else
        {   // no prior list. we're it. self-reference
            *headpp = p;
            p->next = p->prev = p;
        }
        return p;
    }
    
    
    // insert a new value into the list, returns a pointer to the
    //  node allocated to hold the value. this will ALWAYS update
    //  the given head pointer, since the new node is being prepended
    //  to the list and by-definition becomes the new head.
    list_t *list_prepend(list_t **headpp, const char* value)
    {
        list_append(headpp, value);
        if (!(headpp && *headpp))
            return NULL;
        *headpp = (*headpp)->prev;
        return *headpp;
    }
    
    
    // insert a new node previous to the given valid node pointer.
    // returns a pointer to the inserted node, or NULL on error.
    list_t *list_insert_before(list_t* node, const char* value)
    {
        // node *must* be a valid list_t pointer.
        if (!node)
            return NULL;
        list_prepend(&node, value);
        return node;
    }
    
    
    // insert a new node after the given valid node pointer.
    // returns a pointer to the inserted node, or NULL on error.
    list_t *list_insert_after(list_t* node, const char* value)
    {
        // node *must* be a valid list_t pointer.
        if (!node)
            return NULL;
        node = node->next;
        list_prepend(&node, value);
        return node;
    }
    
    
    // delete a node referenced by the node pointer parameter.
    //  this *can* be the root pointer, which means the root
    //  must be set to the next item in the list before return.
    int list_remove(list_t** headpp, list_t* node)
    {
        // no list, empty list, or no node all return immediately.
        if (!(headpp && *headpp && node))
            return 1;
    
        // validate the node is in *this* list. it may seem odd, but
        //  we cannot just free it if the node may be in a *different*
        //  list, as it could be the other list's head-ptr.
        if (*headpp != node)
        {
            list_t *p = (*headpp)->next;
            while (p != node && p != *headpp)
                p = p->next;
            if (p == *headpp)
                return 1;
        }
    
        // isolate the node pointer by connecting surrounding links.
        node->next->prev = node->prev;
        node->prev->next = node->next;
    
        // move the head pointer if it is the same node
        if (*headpp ==  node)
            *headpp = (node != node->next) ? node->next : NULL;
    
        // finally we can delete the node.
        free(node->value);
        free(node);
        return 0;
    }
    
    
    // release the entire list. the list pointer will be reset to
    //  NULL when this is finished.
    void list_free(list_t **headpp)
    {
        if (!(headpp && *headpp))
            return;
        while (*headpp)
            list_remove(headpp, *headpp);
    }
    
    
    // enumerate the list starting at the given node.
    void list_foreach(list_t *listp, void (*function)(const char*))
    {
        if (listp)
        {
            list_t *cur = listp;
            do {
                function(cur->value);
                cur = cur->next;
            } while (cur != listp);
        }
        printf("\n");
    }
    
    // printer callback
    void print_str(const char* value)
    {
        printf("%s\n", value);
    }
    
    // main entrypoint
    int main(int argc, char *argv[])
    {
        list_t *listp;
        list_init(&listp);
    
        // insert some new entries
        list_t* hello =   list_append(&listp, "Hello, Bedrock!!");
        assert(NULL != hello);
        assert(listp == hello);
    
        // insert Fred prior to hello. does not change the list head.
        list_t* fred = list_insert_before(hello, "Fred Flintstone");
        assert(NULL != fred);
        assert(listp == hello);
        // Hello, Bedrock!!
        // Fred Flintstone
        list_foreach(listp, print_str);
    
        // insert Wilma priot to Fred. does not change the list head.
        list_t* wilma = list_insert_before(fred, "Wilma Flintstone");
        assert(NULL != wilma);
        assert(list_next(wilma) == fred);
        assert(list_previous(wilma) == hello);
        // Hello, Bedrock!!
        // Wilma Flintstone
        // Fred Flintstone
        list_foreach(listp, print_str);
    
        list_t* barney =  list_prepend(&listp, "Barney Rubble");
        list_t* dino =    list_insert_after(wilma, "Dino");
        assert(barney != NULL);
        assert(dino != NULL);
        assert(listp == barney);
        assert(list_previous(barney) == fred);
        assert(list_next(barney) == hello);
        // Barney Rubble
        // Hello, Bedrock!!
        // Wilma Flintstone
        // Dino
        // Fred Flintstone
        list_foreach(listp, print_str);
    
        // remove everyone, one at a time.
        list_remove(&listp, fred);   // will not relocate the list head.
        // Barney Rubble
        // Hello, Bedrock!!
        // Wilma Flintstone
        // Dino
        list_foreach(listp, print_str);
    
        list_remove(&listp, hello);  // will not relocate the list head.
        // Barney Rubble
        // Wilma Flintstone
        // Dino
        list_foreach(listp, print_str);
    
        list_remove(&listp, barney); // will relocate the list head.
        // Wilma Flintstone
        // Dino
        list_foreach(listp, print_str);
        assert(listp == wilma);
        assert(list_next(wilma) == dino);
        assert(list_previous(listp) == dino);
    
        list_remove(&listp, wilma);  // will relocate the list head.
        // Dino
        list_foreach(listp, print_str);
    
        list_remove(&listp, dino);   // will relocate the list head;
    
        // generate a raft entries (a million of them)/
        char number[32];
        int i=0;
        for (;i<1000000; i++)
        {
            sprintf(number, "%d", i);
            list_append(&listp, number);
        }
    
        // now test freeing the entire list.
        list_free(&listp);
    
        return 0;
    }
    
    Hello, Bedrock!!
    Fred Flintstone
    
    Hello, Bedrock!!
    Wilma Flintstone
    Fred Flintstone
    
    Barney Rubble
    Hello, Bedrock!!
    Wilma Flintstone
    Dino
    Fred Flintstone
    
    Barney Rubble
    Hello, Bedrock!!
    Wilma Flintstone
    Dino
    
    Barney Rubble
    Wilma Flintstone
    Dino
    
    Wilma Flintstone
    Dino
    
    Dino