Double-linked and circular list, memory errors with Valgrind

Asked

Viewed 32 times

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-connected 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 checking 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)

Can anyone explain to me why?

1 answer

2


You allocate a new list using malloc but it doesn’t have the free corresponding to release this allocated memory. This is visible in the information given by Valgrind

total heap Usage: 1 allocs, 0 Frees, 12 bytes allocated

Notice that you have 1 alloc and 0 free, and you can even 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 the main break up:

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

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.