刚开始学习C。我编写了使用两个指针来释放哈希表的代码,在块的末尾将定义的指针设置为NULL,但似乎代码仍然会导致内存泄漏。想知道为什么。附上代码。
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;
}
导致两个指针内存泄漏
这些声明
node *cur = malloc(sizeof(node));
node *next_node = malloc(sizeof(node));
是内存泄漏的原因,因为首先分配内存并将其地址存储在这些指针中,然后重新分配指针
cur = table[i];
next_node = cur->next;