【问题标题】:Segmentation Fault when deleting complete linked list删除完整链表时出现分段错误
【发布时间】:2010-09-30 17:59:57
【问题描述】:

我正在尝试删除整个链表,但出现分段错误并且无法检测到真正的问题。当我尝试使用 gdb 进行调试时,它能够删除第一个节点,但在删除第二个节点时会引发分段错误。请建议我可能是什么原因。

#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;
    }
}

【问题讨论】:

    标签: c++ data-structures linked-list segmentation-fault


    【解决方案1】:

    因为在 listNode d'tor 中它正在删除下一个节点。所以,当它去删除列表中的第二个节点时,它已经被删除了。

    ~listNode ()
    {
        delete next;
    }
    

    改成...

    ~listNode ()
    {
    }
    

    【讨论】:

      【解决方案2】:

      您要删除head-&gt;next 两次;一次在 listNode 析构函数中,一次在循环中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-08-16
        • 1970-01-01
        • 2017-10-28
        • 2013-04-11
        • 1970-01-01
        • 1970-01-01
        • 2012-01-14
        相关资源
        最近更新 更多