Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructor crash

Tags:

c++

destructor

I am working on a Win32 c++ application in Visual studio.

In one of the source files, I have global object like below.

TestClass tObj;

int main() //Execution starts here
{
}

TestClass is defined in other DLL like below.

struct Source
{

};

class TestClass
{
  list<Source> sourceList;
    public:
         TestClass() {}
        ~TestClass() {}
};

While my application is running, if i try to close the app explicitly, by closing the console window, it is crashing in TestClass destructor. Callstack shows CrtIsValidHeapPointer is failing.

Pls help me to solve this issue.

like image 644
bjskishore123 Avatar asked Aug 13 '10 09:08

bjskishore123


2 Answers

Your problem is that differing compiler/linker settings between the .exe and .dll are effectively causing the .dll and .exe to be using different implementations of the standard library:

  • You must use the same preprocessor flags* to build both the .exe and the .dll, otherwise each binary will compile with subtly different implementations.
  • You must link both both the .exe and the .dll to the dynamic runtime. Binaries linked statically to the runtime get their own heap - and you end up allocating on one heap and trying to free on another.

To fix this, go to Project > Properties > Configuration Properties > C/C++ > Code Generation and change the runtime library option to Multi-threaded Debug DLL (/MDd). You must do this for both the .exe project and the .dll project.

As of Visual Studio 2010, some of these kind of errors will be detected at link time using #pragma detect_mismatch.

*For all preprocessor flags that have any effect of the standard library implementation

like image 140
JoeG Avatar answered Sep 18 '22 15:09

JoeG


Make sure you build bot the EXE and the DLL with the same runtime, preferably with the dynamic runtime.

like image 20
sbi Avatar answered Sep 19 '22 15:09

sbi