簡體   English   中英

C內存泄漏,哪里沒有內存泄漏? (瓦爾格林德)

[英]C memory leak, where there is no memory leak? (valgrind)

valgrind 告訴我代碼中的特定行會造成內存泄漏,但是在查看該行時,它似乎甚至無法創建內存泄漏。

我正在使用這個非常簡單的鏈表結構 list.h:

typedef struct _linekd_list{
    void* object;
    struct _linked_list* next;
}linked_list;

這就是在 list.c 中初始化列表的方式:

linked_list* newlist(){
    linked_list * list = malloc(sizeof(linked_list));
    list->next = NULL;  //As a flag, that there is no next element
    list->object = NULL;
    return list;
}

我的隊列如此工作,第一個linked_list 的第一個對象始終為NULL,第一個對象存儲在下一個linked_list 中。

現在這里是發生內存泄漏的地方:

int list_add(void* new_object, linked_list* list){
        while(list->next != NULL) {  //First go to the end of the queue
            list = list->next;
        }
        list->next = malloc(sizeof(linked_list)); //Vangrind says there is a leak
        list->next->next = NULL; //Set the next list-object to NULL (acts like a flag)
        list->next->object = new_object; //And now store the pointer of the actual object
        if(list->next->object == new_object) {
            return 0;
        } else {
            return 1;
        }
    return 0;
}

這就是 valgrind 告訴我的:

==33369== 16 bytes in 1 blocks are definitely lost in loss record 1 of 3
==33369==    at 0x483B7F3: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==33369==    by 0x402219: list_add (list.c:11)
==33369==    by 0x4012D0: main (test_list.c:38)
==33369== 

這是遞歸釋放列表的函數(未檢測到內存泄漏):

void free_list(linked_list* list){
    if(list->next != NULL) {
        free_list(list->next);
        free(list);
    }
}

您不會釋放列表中的最后一個節點。

如果list->nextNULLfree_list什么也不做。 但你不想什么都不做。 你不想遞歸,但你仍然需要釋放節點。 所以將調用從條件中free ,或者更改測試以檢查list本身是否為NULL

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM