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.
You need a deep-copy constructor to avoid double free(). You have a variable of temp class (a), then you add it to the list. The variable is copied. Then you clear the list, the element inside is destroyed and free() is called. Then a variable is destroyed and free() is called again for the same address which leads to segmentation fault.
You need a copy constructor for deep copying class temp variables which would malloc() another buffer and copy data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With