fraiser
fraiser

Reputation: 969

Destructor segfault in simple LinkedList program

I'm creating a basic linked list in C++, but for some reason my destructor segfaults when I run the program with a signal 11 (which I found using Valgrind). My Link object only has two variables, string value and Link* next

This is the destructor.

Link::~Link() {
  Link* curr = this;
  while (curr != NULL) {
    Link* nextLink = curr->next;
    delete curr;
    curr = nextLink;
 }
}

This is main.cpp

int main() {

  string temp;
  getline(cin, temp);
  Link* head = new Link(temp, NULL);
  Link* tempHead = head;

  for(int i = 1; i < 5; i++) {
    getline(cin, temp);
    Link* newLink = new Link(temp, head);
    head = newLink;
  }
  head->printAll(head);
  head->~Link();

  return 0;

}

EDIT: For link.cpp, I did this-

Link::~Link() {
  Link* curr = this;
  delete curr;
}

And then for main.cpp, I changed head->~Link() to

  Link* curr = tempHead;
  while(curr!=NULL) {
    Link* nextLink = curr->getNext();
    curr->~Link();   //replacing with delete curr gives the same segfault
    curr = nextLink;
  }

Upvotes: 0

Views: 118

Answers (1)

Mikel F
Mikel F

Reputation: 3671

When you execute delete curr; in your destructor, it will call the destructor again for that node, resulting in an endless recursive loop that is probably overflowing your stack.

You should not be calling what is effectively 'delete this' in your destructor.

Instead consider:

Link::~Link() {
      delete next;
}

And in main, simply use delete head;

This is still recursive, which can be problematic with a long list and a small stack. Alternatively, you can put the loop in your main function that walks the list rather than in the destructor. If you want to encapsulate the delete loop in the class itself, add a clear method to perform the loop. Just don't call it from the destructor.

Upvotes: 2

Related Questions