c - CreateList 函数(链表)中的内存泄漏

标签 c memory-leaks linked-list valgrind

我尝试使用带有以下选项的 valgrind 检查内存泄漏:

valgrind --leak-check=full -v ./linkedlist2

Valgrind 说 createList() 函数中存在内存泄漏,但我找不到原因。能否请您帮助我了解内存泄漏的原因是什么?

相关代码:

struct node{
    int data;
    struct node* next;
};

struct node* createList(int num)
{
    struct node* temp = NULL;
    struct node* head = NULL;
    struct node* curr = NULL;

    int i = 0;
    if(num <= 0)
    {
        printf("Invalid size for createList\n");
        return;
    }

    for(i=0;i<num;i++)
    {
        temp = malloc(sizeof(struct node)); //allocate memory
        temp->data = i+1;
        temp->next = NULL;

        if(i == 0)
        {
            head = temp;
            curr = temp;
        }else   {
            curr->next = temp;
            curr = temp;
        }
    }
    curr = temp = NULL;
    //curr->next = temp->next = NULL;
    free(curr);free(temp);
    return head;
}

enter image description here

最佳答案

这一行导致了问题

curr = temp = NULL;
//curr->next = temp->next = NULL;
free(curr);free(temp);

好吧,在这里您将 NULL 分配给结构节点指针 currtemp,此后它指向的内存将变成垃圾。您首先使用 free() 释放内存并将其分配给 NULL

用这个替换你上面的代码

free(curr);
free(temp);
curr = temp = NULL;

关于c - CreateList 函数(链表)中的内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34434690/

相关文章:

c - 将条目附加到链表的末尾

c - C 中链表的指针基址和顶部

c - 使本地 HTTP 服务器无法从外部访问

c - 已分配的内存 - 已分配数组的结构

c - 查找素数的程序打印出两个

java - 这个 Java 示例会导致内存泄漏吗?

c++ - 程序退出后如何跟踪随机 free() 无效指针?

python - 为什么 Python 没有原生的链表实现?

c - 在编译时初始化数组

iphone - iOS5.0.1上的内存泄漏drawInRect