c++ - Dll exporting a constructor risks causing heap corruption -
i working on programme plugin scheme allows users develop own modules in form of dll files. modules supposed utilize objects defined in dll imported components of application. here sample object like:
#include <boost/system/api_config.hpp> #if defined boost_windows_api #ifdef export #define api __declspec(dllexport) #else #define api __declspec(dllimport) #endif #else #define api #endif class { public: api a(); api virtual ~a(); }; all dlls built statically (with own crt) , exact same compilation flags. know exchanging objects through dll boundaries can hairy, utilize boost::shared_ptrs everywhere. there 1 difficulty around object constructors though: if create object on stack (from different dll), works expected. if utilize operator new, heap gets corrupted whet object deleted.
a a; // works fine, no problem when object goes out of scope. a* b = new a(); delete b; // causes heap corruption! what proper way around this? sense code less readable if had define method in object's dll such a* a::create() { homecoming new a(); }. in worst scenario, i'm thinking of making new operator private, create sure user won't utilize it.
based on responsed comments: /mt , /mtd don't work dlls (even if default). if want utilize dlls , dynamic allocation, must utilize /md or /mdd. when utilize /mt or /mtd, tell scheme utilize separate heap each dll. means allocating in one, , deleting in corrupt heap. , when destructor virtual, actual delete in destructor, not in delete expression. (the actual issue malloc , free, called operator new() , operator delete() functions.)
the classical way of working around utilize mill methods dynamic allocation , static or fellow member function delete. alternative (not tried, think work) defined non-inline operator new() , operator delete() members, forwards malloc , free. (in case of operator new, of course, have check pointer malloc isn't null, , throw std::bad_alloc if is.)
but these work-arounds situation shouldn't exist. works fine /md or /mdd, , should using (even if means can't legally deploy debug version on machines don't have license visual studios).
c++ dll
No comments:
Post a Comment