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
These declarations
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
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
contains a duplicated code.
And these statements
invoke undefined behavior due to using null pointers to access memory.
Also the return type
boolof the function does not make a great sense.