Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Seg fault after is item pushed onto STL container

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.

like image 217
FL4SOF Avatar asked Nov 26 '22 23:11

FL4SOF


2 Answers

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.

like image 74
Binary Worrier Avatar answered Dec 20 '22 05:12

Binary Worrier


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.

like image 32
sharptooth Avatar answered Dec 20 '22 05:12

sharptooth