MATLAB: Does the MEX file that uses another DLL cause MATLAB to crash

crashdllheapinvalidMATLABpointerstdstlwindows

I have created a MEX file in C++. This MEX file uses another DLL that is present on the system. When I attempt to execute the MEX file from within MATLAB everything works fine (verified stepping through the mex code inside Visual Studio 2008) until the MEX file needs to return to MATLAB. At this point a memory crash is detected and MATLAB quits.
This also happens when I am using STL objects.

Best Answer

There are several factors that can contribute to MATLAB crashing. In Windows, a common mistake is the freeing of the DLL or the STL object is not performed where it was allocated.
The programmer should explicitly control the allocation and deallocation of the objects. If done improperly, the allocation occurs on a separate heap from MATLAB and cause a crash.
To workaround this issue, ensure the memory is freed with the same allocator that allocated it.
For DLLs, another workaround is to ensure it uses MSVC 2005 so it shares the same runtime heap as MATLAB.