Double linked list and circular, memory errors with valgrind

1

I have the following structures:

typedef struct Node
{
    char info[40];
    struct Node *ant;
    struct Node *prox;
}NoCDup;

typedef struct LDEC
{
    NoCDup *cabeca;
    NoCDup *cauda;
    int tamanho;
}ListaCDup;

And also the function that initializes the double-linked and circular list:

ListaCDup *criar()
{
    ListaCDup *p = (ListaCDup*) malloc (sizeof(ListaCDup));
    p->cabeca = p->cauda = NULL;
    p->tamanho = 0;
    return p;
}

And in main simply:

int main(){

    ListaCDup *l = criar();


    ImprimeListaCDup(l);
    return 0;
}

But when I check for memory errors with valgrind, I have the following problem:

==10879==     in use at exit: 12 bytes in 1 blocks
==10879==   total heap usage: 1 allocs, 0 frees, 12 bytes allocated
==10879== 
==10879== 12 bytes in 1 blocks are definitely lost in loss record 1 of 1
==10879==    at 0x482E27C: malloc (vg_replace_malloc.c:299)
==10879==    by 0x10869E: criar (in /home/student/Downloads/lista)
==10879==    by 0x108D3B: main (in /home/student/Downloads/lista)

Does anyone know why?

    
asked by anonymous 03.10.2018 / 20:09

1 answer

2

You allocate a new list using malloc but do not have the corresponding free to release that allocated memory. This is visible in the information given by valgrind

  

total heap usage: 1 allocs, 0 frees, 12 bytes allocated

Note that you have 1 alloc and 0 free, and you can see that on your machine the space used by the structure is 12 bytes.

Assuming you will need the list during the course of the entire program, you can release it at the end, before main finishes:

int main(){
    ListaCDup *l = criar();

    ImprimeListaCDup(l);
    free(l); //<-- liberar a lista alocada anteriormente
    return 0;
}

If you no longer need this list before the end you should release it immediately. The release should be made as early as possible, from the point where you do not need it.

    
03.10.2018 / 20:24