简体   繁体   中英

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

I have a function that allocates memory for a pair in a linked list and when I run, valgrind says I'm not freeing the memory. Here is my function:

#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);
}

When I use in my main, assignPair(p), it says the following:

==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)

Can anyone please tell me where I'm making a mistake? I read through the manual of valgrind here: Link to valgrind man page

But that still doesn't help me.

Valgrind check for memory leaks . So when you allocate your memory for a structure or function you should free the memory when it is no longer needed. In your program you had allocated using malloc twice and has not freed the memory allocated.

So you should free the memory created some where in the code.

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

ie in your code exactly

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

Remember the order in which you free the memory is also factor as you will get a segmentation fault for illegal memory access.

In your main function, you allocate memory:

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

At the end of the function, a goes out of scope, and it was the last pointer referring to that memory. You need to provide a freePair() function in order to release the memory while it's still reachable through a :

{
    a = assignPair(p);
    /* perhaps some other operations here */
    freePair(a);
}

The implementation of freePair() should be very straightforward.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM