如何释放堆中的内存而不会在链表中发生内存泄漏

问题描述 投票:0回答:2

我写了一个函数来处理链表中的内存释放,但该函数能够释放它们,但我遇到了内存泄漏。请有人告诉我为什么这个函数能够释放我的内存但是有内存泄漏。

void free_listint(listint_t *head)
{
    listint_t *temp;
     
    temp = head;
    while (head != NULL)
    {
         free(head);
         temp = temp->next;
    }
    return;
}
c linked-list malloc singly-linked-list
2个回答
2
投票

你的 while 循环检查 head 但 head 永远不会在循环内重新分配。这可能会导致无限循环,

temp = temp->next;
最终可能会崩溃。

我建议像这样重写

void free_listint(listint_t *head)
{
    listint_t *temp;
     
    while (head != NULL)
    {
         temp = head->next;
         free(head);
         head = temp;
    }
    return;
}

1
投票

@Karthick 显示了 OP 的错误和一种解决方案。 (信用!)

为了好玩,以下可能扫描稍微简单一点:

void free_listint( listint_t *head )
{
    while( head )
    {
        // strive to limit the scope of variables
        listint_t *del = head;
        head = head->next;
        free( del );
    }
    // return; // this is unnecessary. write less code.
}
© www.soinside.com 2019 - 2024. All rights reserved.