Memory leak in C: free a hashtable

60 Views Asked by At

just begin learning C. I wrote code using two pointers to free a hashtable, setting the defined pointers to NULL at the end of the block, but it seems that the code still cause memory leak. Wonder why. Code attached.

bool unload(void)
{
    // 2 linked-list node to free a hashtable
    node *cur = malloc(sizeof(node));
    node *next_node = malloc(sizeof(node));
    // traverse the hashtable
    for (int i = 0; i < N; i++)
    {
        if (table[i] != NULL)
        {
            cur = table[i];
            next_node = cur->next;
            free(cur);
            cur = NULL;
            while (next_node != NULL)
            {
                cur = next_node;
                next_node = next_node->next;
                free(cur);
                cur = NULL;
            }
        }
    }
    cur = NULL;
    next_node = NULL;
    printf("cur, next, %s,%s",cur->word,next_node->word);
    return true;


}

resulting in memory leak on two pointers

1

There are 1 best solutions below

0
Vlad from Moscow On

These declarations

node *cur = malloc(sizeof(node));
node *next_node = malloc(sizeof(node));

are reasons of memory leaks because at first a memory is allocated and its address is stored in these pointers and then the pointers are reassigned

cur = table[i];
next_node = cur->next;

Pay attention to that it is not a good idea when functions depend on global variables as your function depends on the variable table.

And this code snippet

for (int i = 0; i < N; i++)
{
    if (table[i] != NULL)
    {
        cur = table[i];
        next_node = cur->next;
        free(cur);
        cur = NULL;
        while (next_node != NULL)
        {
            cur = next_node;
            next_node = next_node->next;
            free(cur);
            cur = NULL;
        }
    }
}

contains a duplicated code.

And these statements

cur = NULL;
next_node = NULL;
printf("cur, next, %s,%s",cur->word,next_node->word);

invoke undefined behavior due to using null pointers to access memory.

Also the return type bool of the function does not make a great sense.