typedef struct temp { int a,b; char *c; temp(){ c = (char*)malloc(10);}; ~temp(){free(c);}; }temp; int main() { temp a; list<temp> l1; l1.push_back(a); l1.clear(); return 0; }
giving segmentation fault.
You don’t have a copy constructor.
When you push ‘a’ into the list, it gets copied. Because you don’t have a copy constructor (to allocate memory for c and copy from old c to new c) c is the same pointer in a and the copy of a in the list.
The destructor for both a’s gets called, the first will succeed, the second will fail because the memory c points to has already been freed.
You need a copy constructor.
To see whats happening, put some couts in the constructors and destructors and step through the code.