Handwritten linked list is segfaulting and I don't understand why
- by Born2Smile
Hi I was working on a bit of fun, making an interface to run gnuplot from within c++, and for some reason the my linked list implementation fails.
The code below fails on the line plots-append(&plot). Stepping through the code I discovered that for some reason the destructor ~John() is called immediately after the constructor John(), and I cannot seem to figure out why.
The code included below is a stripped down version operating only on Plot*. Originally I made the linked list as a template class. And it worked fine as ll<int and ll<char* but for some reason it fails as ll<Plot*.
Could youp please help me figure out why it fails? and perhaps help me understand how to make it work?
In advance: Thanks a heap!
//B2S
#include <string.h
class Plot{
char title[80];
public:
Plot(){ }
};
class Link{
Plot* element;
Link* next;
Link* prev;
friend class ll;
};
class ll{
Link* head;
Link* tail;
public:
ll(){
head = tail = new Link();
head-prev = tail-prev = head-next = tail-next = head;
}
~ll(){
while (head!=tail){
tail = tail-prev;
delete tail-next;
}
delete head;
}
void append(Plot* element){
tail-element = element;
tail-next = new Link();
tail-next-prev = tail;
tail-next = tail;
}
};
class John{
ll* plots;
public:
John(){
plots= new ll();
}
~John(){
delete plots;
}
John(Plot* plot){
John();
plots-append(plot);
}
};
int main(){
Plot p;
John k(&p);
}