3

我正在使用链表并填充结构,但是当我删除整个结构并尝试打印链表的内容(应该为空)时,会出现一个数字列表。我知道这可能是内存问题。有关如何解决它的任何建议?

删除整个链表的代码:

void destroy(set_elem *head)
{
    set_elem *current = head;
    set_elem *next;

    while (current != NULL)
    {
       next = current->next;
       free(current);
       current = next;
    }
    head = NULL;
}
4

4 回答 4

2

虽然您的delete函数正常工作,但当您这样做时,它不会将调用者中的head设置为 NULL,head = NULL;因为您只是在修改本地指针,这会导致您稍后的逻辑您试图通过检查值来打印值head.

要修改原始指针,请将指针传递给head并设置*head=NULL;

void destroy(set_elem **head)
{
set_elem *current = *head;

/* rest is the same */

*head = NULL;
}
于 2013-10-19T21:46:22.397 回答
1

你没有改变原来的头。您应该将指针传递给此头,即指向指针的指针,或者应该将更改的头返回给调用者。以下是将更改的头部返回给调用者的代码。还有其他答案显示指向指针方法的指针。

  set_elem* destroy(set_elem *head) {
      set_elem *current = head;
     set_elem *next;

     while (current != NULL) {
         next = current->next;
         free(current);
         current = next;
     }
     head = NULL;
     return head;
   }

在来电者中,

    head = destroy(head);
于 2013-10-19T22:24:49.587 回答
1

当您将头指针复制到函数中时,头节点不受影响。您必须将指针的引用传递给头,然后您才能删除头指针。这也可以通过将指针传递给指向链表头部的指针来完成,但我发现传递引用更方便。以下是对您的代码的更改。

void destroy(set_elem*& head)
{

  set_elem* current = head;
  set_elem* next;

  while (current != NULL)
  {
       next = current->next;
       free(current);
       current = next;
  }

   *head = NULL;
}
于 2013-10-19T22:05:30.023 回答
0

You're modifying only the local head pointer

Use a double pointer to modify the head, which would be later used for printing/processing

void destroy(set_elem** head)
{

   set_elem* current = *head;
   set_elem* next;

   while (current != NULL)
   {
       next = current->next;
       free(current);
       current = next;
   }

   *head = NULL;
}
于 2013-10-19T21:48:45.743 回答