Valgrind 说我没有释放内存,这是为什么?

Valgrind says i'm not freeing the memory, why is that?

我有一个函数为链表中的一对分配内存,当我 运行 时,valgrind 说我没有释放内存。这是我的功能:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct{
int id;
char type;
}Pair;

typedef struct cel{
void *info;
struct cel *urm;
}Celula, *TLista, **ALista;


TLista assignPair(Pair p){

TLista new_entry = malloc(sizeof(Celula));
if (!new_entry){
    return NULL;
}

new_entry->info = malloc(sizeof(Pair));
if (!new_entry->info){
    free(new_entry);
    return NULL;
}

new_entry->urm = NULL;

((Pair*)new_entry->info)->id = p.id;
((Pair*)new_entry->info)->type = p.type;

return new_entry;

}

int main(){
Pair p;
p.id = 2;
p.type = 'c';
TLista a;
a = assignPair(p);
}

当我在 main 中使用 assignPair(p) 时,它表示如下:

==4068== 24 (16 direct, 8 indirect) bytes in 1 blocks are definitely lost in loss record 2 of 2
==4068==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4068==    by 0x40057B: assignPair (in /home/vaduva/SD/2017/Tema2/example)
==4068==    by 0x40060B: main (in /home/vaduva/SD/2017/Tema2/example)

谁能告诉我哪里出错了?我在这里通读了 valgrind 的手册:Link to valgrind man page

但这仍然对我没有帮助。

Valgrind 检查 memory leaks。因此,当您为结构或函数分配内存时,您应该在不再需要时 free the memory 。在您的程序中,您使用 malloc 分配了两次,并且没有释放分配的内存。

所以你应该释放在代码中某处创建的内存。

free(new_entry->info);
free(new_entry);

即在您的代码中

int main() {
Pair p;
p.id = 2;
p.type = 'c';
TLista a;
a = assignPair(p);
free(a->info);
free(a);
}

记住释放内存的顺序也是一个因素,因为非法内存访问会导致分段错误。

在你的主函数中,你分配了内存:

{
    a = assignPair(p);
} // leaked

在函数结束时,a 超出范围,它是指向该内存的最后一个指针。您需要提供一个 freePair() 函数,以便在内存仍然可以通过 a:

访问时释放内存
{
    a = assignPair(p);
    /* perhaps some other operations here */
    freePair(a);
}

freePair() 的实现应该非常简单。