0

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

2 Answers 2

4

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 ()
{
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.