MATLAB: How to destroy a structure array from a C MEX-file used in MATLAB

crashdestroyMATLABmexstructure

I have a C MEX-file that creates and destroys a structure as follows:
mxArray *myDataOne;
mxArray *myDataTwo;
mxArray *aStruct;
const char *fields[] = { "one", "two" };
myDataOne = mxCreateDoubleScalar(1.0);
myDataTwo = mxCreateDoubleScalar(2.0);
aStruct = mxCreateStructMatrix(1,1,2,fields);
mxSetField( aStruct, 0, "one", myDataOne );
mxSetField( aStruct, 0, "two", myDataTwo );
mxDestroyArray(myDataOne);
mxDestroyArray(myDataTwo);
mxDestroyArray(aStruct);
When I call the MEX-file repeatedly, I receive the following crash:
Assertion failed: Forced Assertion at line 714 of file ".\memmgr\mem32aligned.cpp".
Corrupted memory block found
Stack Trace:
[0] bridge.dll:_mnSignalHandler(0xffffffff, 0, 0, 0x79d8c450) + 350 bytes
[1] bridge.dll:void __cdecl ThrowAssertion(void)(0x01200068, 0x01cc0000, 0x65737341, 0x6f697472) + 152 bytes
[2] bridge.dll:void __cdecl MATLABAssertFcn(char const *,char const *,int,char const *)(0x7849c57c ": Forced Assertion", 0x7849cc08 ".\memmgr\mem32aligned.cpp", 714, 0x7849cfb4 "Corrupted memory block found") + 110 bytes
[3] libut.dll:_mw_malloc32(7, 0, 0x00d0dae8, 0x7847cd67) + 283 bytes
[4] libut.dll:_mw_calloc32(7, 1, 0, 0x00d0db04 " ÛÐ") + 17 bytes
[5] libut.dll:_utCalloc(7, 1, 0x01cca188 "uiopen", 6) + 119 bytes
[6] jmi.dll:_ojJavaClassOfMatlabClassName(0x01cca188 "uiopen", 6, 0x02355ca9

Best Answer

The documentation for MATLAB 7.6 (R2008a) has been updated to incorporate the relevant information. For previous product releases, read below for any possible workarounds:
Documentation on destroying structure arrays is not available in MATLAB 7.2 (R2006a). Here is additional information on destroying structure arrays in MATLAB:
If you create a structure matrix or array and use mxSetField or mxSetFieldByNumber to put another mxArray's data into the structure, it is not copied, rather the structure's field points to the other mxArray. When the structure is destroyed, it attempts to traverse down through itself and free all other data. Therefore, if the data array is destroyed and then the structure array is destroyed, the same memory is freed twice.
To workaround this issue, destroy the structure only as follows:
mxArray *myDataOne;
mxArray *myDataTwo;
mxArray *aStruct;
const char *fields[] = { "one", "two" };
myDataOne = mxCreateDoubleScalar(1.0);
myDataTwo = mxCreateDoubleScalar(2.0);
aStruct = mxCreateStructMatrix(1,1,2,fields);
mxSetField( aStruct, 0, "one", myDataOne );
mxSetField( aStruct, 0, "two", myDataTwo );
mxDestroyArray(aStruct);