I’m running into a strange crash. I am trying to separate out various modules of my Application (MFC based, developed in VS2005) into DLLs. Following is the skeletal code of how I’m trying to achieve it:
In a common Header file(say base.h):
class Base {
vector<message> messages;
...
...
};
In a header file in DLL source code(say class.h):
class Derived : public Base {
private:
int hoo();
...
public:
void foo();
int goo();
...
};
extern "C" __declspec (dllexport) Derived* CreateDerived();
In class.cpp
Derived* CreateDerived()
{
return new Derived;
}
In a file in main Application code:
#include "base.h"
#include "class.h"
typedef Derived* (*DerivedCreator)();
...
...
void LoadDll()
{
//DLL Load Code...
...
...
DerivedCreator creator = reinterpret_cast<DerivedCreator>(::GetProcAddress(dllHandle, "CreateDerived"));
Derived* pDerived = creator();
pDerived->messages.push_back(message("xyz"));//Crashes here...
}
The problem is the code craches the moment I try to access the vector member of the Base class. This only happens in Release mode. It works fine in Debug mode. The error message that i get when I execute it from Visual Studio in Release mode is:
“Microsoft Visual Studio C Runtime Library has detected a fatal error in Samsung SSD Magician.exe.
Press Break to debug the program or Continue to terminate the program.”
But when I execute the release binary directly and attach the debugger to it, I get an Access Violation. At this point if I check the vector in debugger, it shows 6-digit entries in it, none of them readable. I’m able to see correct values of rest of the members of Base class in the Derived pointer.
Any help would be much appreciated.
It’s dangerous to pass stl containers across a DLL boundary.
The reason here is that each module (the main application and the DLL) has it’s own instance of the heap. If you allocate dynamic memory in the context of DLL, then pass the pointer to the application and release that memory in the context of the application, that causes heap corruption.
That is exactly what happens in your example.
CreateDerivedis called.new Derivedallocates memory in DLL heap.Inside
push_back, an additional memory is allocated forBase::messages, and that allocation is done on the application heap. Crash!A conclusion is that you need to rethink the DLL interface in order to perform all operation on the vector only inside the DLL.