简体   繁体   English

删除完整的链表时出现分段错误

[英]Segmentation Fault when deleting complete linked list

I'm trying to delete whole linked list but getting segmentation fault and not able to detect what is the real problem. 我正在尝试删除整个链表,但出现分段错误,无法检测出真正的问题。 When I tried debugging using gdb, it is able to remove the first node but throw segmentation fault when deleting second node. 当我尝试使用gdb进行调试时,它能够删除第一个节点,但是在删除第二个节点时会引发分段错误。 Please suggest me what can be the possible reason. 请建议我可能是什么原因。

#include <iostream>
using namespace std;
class listNode
{
public:

    listNode *next;
    char data;

    listNode ()
    {
        next = NULL;
        data = '\0';
    }

    listNode (char alphabet)
    {
        next = NULL;
        data = alphabet;
    }

    ~listNode ()
    {
        delete next;

    }
};


class linkedList
{
public:

    listNode *head;
    void insert (listNode * node);
    trieNode *search (char alphabet);

    linkedList ();
    ~linkedList ();
    void printList ();

private:
    void deleteCompleteList ();

};

int
main ()
{
    linkedList testList;
    for (int i = 0; i < 10; i++)
    {
      listNode *temp = new listNode ('a' + i);
      testList.insert (temp);
    }

  testList.printList ();


}


linkedList::linkedList ()
{
  linkedList::head = NULL;
}

linkedList::~linkedList ()
{
  linkedList::deleteCompleteList ();
}

void
linkedList::printList ()
{
  listNode *temp = head;
  while ( temp )
  {
          cout << temp->data << endl;
          temp = temp->next;
  }

}

void
linkedList::insert (listNode *node)
{
    node->next = head;
    head = node;
}

trieNode *
linkedList::search (char alphabet)
{
    listNode *temp = head;
    while (temp)
    {
        if (temp->data == alphabet)
            return temp->down;
        temp = temp->next;
    }

    return NULL;
}

void
linkedList::deleteCompleteList ()
{
    listNode *temp ;
    while ( head )
    {
        temp = head;
        head = head->next;
        delete temp;
    }
}

Because in the listNode d'tor it's deleting the next node. 因为在listNode d'tor中,它正在删除下一个节点。 So, when it goes to delete the second node in the list, it's already deleted. 因此,当要删除列表中的第二个节点时,它已被删除。

~listNode ()
{
    delete next;
}

Change it to... 更改为...

~listNode ()
{
}

You're deleting head->next twice; 您要删除head->next两次; once in the listNode destructor, and once in the loop. 一次在listNode析构函数中,一次在循环中。

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

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