Re: segmentation fault when window closes



El Sep 22, 2010, a las 6:14 PM, Piscium <groknok gmail com> escribió:

> I have a gtkmm application that crashes with a segmentation fault when
> I close the main window.
> 
> It makes use of a class called "Object", that has a member called
> "name", of type ustring. If I comment out that member the program does
> not crash, so the crash is somehow related to ustring.
> 
> Then I have a vector of Objects. If I comment out the push_back's the
> program does not crash. This means that the crash happens when the
> vector dtor does its business on the ustring's. To confirm this I
> explicitly called the clear method of the vector before the end of the
> main function, and then the crash happens there instead of at the end
> of the program.
> 
> I created a example program to summarize the relevant details of my
> application. It is listed below. Interestingly the example does _not_
> crash. But I must be doing something wrong, and the fact that the
> example does not crash must be a coincidence. I wonder if anybody can
> spot what is wrong?
> 
> =================
> 
> #include <iostream>
> #include <vector>
> 
> #include <glibmm/ustring.h>
> 
> using Glib::ustring;
> 
> class Object
> {
> public:
> Object(int id, char * name) : id(id), name(name) {};
> 
> int id;
> ustring name;
> };
> 
> int main(int argc, char** argv)
> {
> std::vector <Object> objects;
> objects.reserve(100);
> 
> for (int i = 0; i < 100; i++)
> {
>         Object o(i, (char *) "hello");
> 
>         objects.push_back(o);
> }
> 
> objects.clear(); // there is a segmentation fault here in the "real"
> application
> }

Sorry to post late to this thread.  At this point I'm not sure what  I'm about to say will be useful, but one other way to deal with objects in code would be to create your objects dynamically (using new) and store them as pointers in the vector.  If you're worried about freeing them when they're not needed, store them in a std::auto_ptr<> in the vector.  This would avoid possible problems with copy constructors and assignment operators not being explicitly defined.  It would also save time from having to copy the objects to store them in the vector.

--
José


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]