Search code examples
cdata-structuresvalgrind

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.


Solution

  • 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.