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

标签 c data-structures valgrind

我有一个函数为链表中的一对分配内存,当我运行时,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 检查内存泄漏。因此,当您为结构或函数分配内存时,您应该在不再需要时释放内存。在您的程序中,您使用 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);
}

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

关于c - Valgrind 说我没有释放内存,这是为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43663700/

相关文章:

java - 这里是否有不使用 getter 和 setter 的情况?

C - 在函数中重新分配指针类型的结构成员变量。 Valgrind 报告 "Invalid read/write of size 1"

c - 奇怪的 C 函数声明

c - 从/dev/input读取

python - 如何选择一个好的Python列表数据结构来存储每一种可能的井字棋游戏

c++ - 在 C++ 中优化 IO

c - Valgrind 错误 : failed in UME with error 22

c - 使用 gprof 的奇怪分析输出

c - 如何将服务器的日期时间转换为unix时间戳?

c++ - 在 C++ 中具有唯一条目的队列