views:

75

answers:

2

Hello,

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. 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;
    }
}
+4  A: 

Because in the listNode d'tor it's deleting the next node. So, when it goes to delete the second node in the list, it's already deleted.

~listNode ()
{
    delete next;
}

Change it to...

~listNode ()
{
}
dgnorton
thanks a lot for pointing it out.
GG
+1  A: 

You're deleting head->next twice; once in the listNode destructor, and once in the loop.

Oli Charlesworth