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