C++: program crashes on exit on std::string destructor
Hi everybody,
i am wondering why the following simple code causes a segfault on exit,when the std::string destructor is called. Quote:
Why does it segfault? |
The typical implementation of an STL object is to allocate space on the heap for the actual data. So if you zero the structure that contains the pointer to that data, you will get a segment violation when it tries to use the pointer (probably when it calls the destructor at the end of the program).
Anyway, in C++ you could have written a constructor inside your struct, rather than zeroing it externally. |
Thank you for the reply :-)
I have a further question,though.... The project i "inherited" makes a terribly large use of memset to zero of various structures. Replacing all of them is a daunting task, and, besides,i can't even do it for some of them,so i ask: 1)What about structures composed ONLY by native integral data types? I guess i can leave "their" memsets with no harm... Is it right? 2)What about structures with methods? Is it ok to memset them to zero? |
Quote:
You are correct in avoiding memset in typical applications, because such functions effectively break the strong type checking, which results in a whole class of potential bugs that the compiler cannot pick up at compile time. Quote:
The only caveat is for virtual methods, because these are typically implemented using a vtable pointer at the beginning of the object (instance of a struct or class). This also applies if any objects in the parent hierarchy have a virtual method. |
Quote:
If so, you would need to look at the source code of the specific implementation of std::string. Quote:
So ints, floats, pointers, etc. and substructures of those should all be OK. I would have warned you about virtual methods in the class or any base class or any member or base class of member, etc. But neonsignal gave a good enough warning on that topic. Don't do any memset that would overwrite any object's vtable pointer. |
All times are GMT -5. The time now is 10:42 PM. |