Handwritten linked list is segfaulting and I don't understand why
Posted
by Born2Smile
on Stack Overflow
See other posts from Stack Overflow
or by Born2Smile
Published on 2010-03-11T21:00:52Z
Indexed on
2010/03/11
21:04 UTC
Read the original article
Hit count: 476
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);
}
© Stack Overflow or respective owner