简体   繁体   English

递归删除链表,使用new分配内存

[英]Recursively deleting a linked list, memory was allocated using new

void DeleteList(node** Head)
{
  if(*Head==NULL)
    return;
  node* current=*Head;
  delete[] current;
  current=NULL;
  DeleteList(&((*Head)->next));
}

The program crashes with a segmentation fault. 程序因分段错误而崩溃。

You need to copy (*Head)->next into another variable before you delete[] current . 您需要在delete[] current之前将(*Head)->next复制到另一个变量中。 Otherwise, you're trying to access next in a node that has been deleted. 否则,您将尝试访问已删除的节点中的next一个节点。

void DeleteList(node** Head)
{
  if(*Head==NULL) {
    return;
  }
  node* current=*Head;
  node* tail = current->next;
  delete current;
  DeleteList(&tail);
}

Also, I doubt you should be using delete[] . 另外,我怀疑您应该使用delete[] current is presumably just a single node, not an array of nodes. current大概只是一个节点,而不是节点数组。 And there's no need to set current = NULL ; 无需将current = NULL设置current = NULL this is a local variable that's just going to go away when the function ends, and you never used it afterward, so it doesn't matter what it contains. 这是一个局部变量,在函数结束时将消失,并且您以后都不会使用它,因此它包含的内容无关紧要。

Another solution would be to simply move DeleteList(&((*Head)->next)); 另一种解决方案是简单地移动DeleteList(&((*Head)->next)); to before delete current; delete current;之前delete current; .

I'm also not sure why you call this function using a pointer to a pointer. 我也不确定为什么要使用指向指针的指针来调用此函数。 That's usually done when you want to modify the caller's pointer. 当您要修改调用者的指针时,通常可以完成此操作。 But you never do that here. 但是您永远不会在这里这样做。 But perhaps you're doing it for consistency with the rest of the linked list library, and that's OK. 但是,也许是为了与链接列表库的其余部分保持一致而这样做,没关系。

Here is some idea what you have to do. 这是您必须要做的一些想法。 accessing the memory after deleting is undefined behavior ( as Barmar's comments ) 删除后访问内存是未定义的行为( 如Barmar的评论

void deleteList(list_link* item)
{
    while (item)
    {
        list_link* old = item;
        item = item->next;
        delete old;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM