Debug assertion failed error when passing std::str

2019-05-18 15:48发布

问题:

I have a C# form calling to a c++/cli interface DLL, which calls off to a win32 native c++ dll. Originally this was written in VS2010, and was working - I was able to marshal a System::String to a std::string, pass it to the native dll, and cout the value. I then converted the C# and c++/cli projects to VS2012 to enable intellisense. This required a service pack install to reenable the 4.0 .NET framework in VS2010. I rebuilt the Win32 dll in 2010, the C# app and c++/cli dll in VS2012, and now I receive an error on the call to the dll:

Debug Assertion Failed!

Program: ... File: f:\dd\vctools\crt_bld\self_x86\crt\src\dbgheap.c Line: 1424

Expression: _pFirstBlock == pHead

public ref class ManagedWrapper
{
    CSampleWin32Library* m_pUnmanagedWrapper;


public:
    ManagedWrapper() {m_pUnmanagedWrapper = new CSampleWin32Library();}
    ~ManagedWrapper() {delete m_pUnmanagedWrapper;}

    //Test call to prove integration
    void Test(int x, System::String^ testString) {
        //marshaling example: http://msdn.microsoft.com/en-us/library/bb384865.aspx         
        std::string tmpStdString = marshal_as<std::string>(testString);
        m_pGambitUnmanagedWrapper->Test(x, tmpStdString); //ERROR OCCURS HERE
    };      
};

Hopefully this is as easy as some setting that was lost, or is now required in VS2012. I didn't change any code otherwise, as far as I know.

回答1:

This error mostly is because of that a block of memory which you malloc in Heap A is freed in Heap B.

You should have a look at Windows Via C/C++--Part IV Dynamic-Link Libraries.

The application will call CRT when it's running.

There two ways to invoke CRT--link to the DLL C/C++ run-time library or link to the static C/C++ run-time library and there different versions of CRT.

All of them use different Memory Management.

So, you should be careful when you free the memory and your code linked to DLL.



标签: c++-cli