MATLAB: Can I replace mxmalloc() and mxfree() function calls to malloc() and free() in the existing C MEX S functions. If yes, what precautions do I need to take in Simulink 7.6 (R2010b)

simulink

I am developing an add on to MATLAB/Simulink and until now, I have been using the mx* functions to do memory management within the C MEX S-Functions.
Recently, I discovered the following article:
<http://www.mathworks.com/support/solutions/en/data/1-5RMJID/?solution=1-5RMJID>
This suggests that mxMalloc and mxFree() should not be used in C MEX functions and malloc() and free() should be used instead. I haven't noticed any bad behavior from the mx* functions as of yet, so I was wondering if this is a really serious issue.

Best Answer

In order to switch from the use of existing mxmalloc() and mxfree() function calls to malloc() and free() you need to take sufficient care about the following:
1. It is highly recommend switching the use of mxmalloc()/mxfree() to malloc()/free() respectively in C MEX S function. This is only applicable for the cases that you have directly assigned a mx* pointer in your S function and call it directly into S function itself.
NOTE: In the case of using an indirect call to an mx* pointer in your S function you would have to dereference it with a pointer of type mx* and also free it using mxfree() only. This implementation cannot be changed moving forward as there is no common pointer interface between MATLAB and Simulink.
2. Moving forward you can simply replace the existing mxmalloc() and mxfree() functions with malloc() and free() counterparts for except those indirect cases that are mentioned above.
On a side note, when using a pointer to an mxArray in a MEX file and using it in an S function, you have to force it to be persistent, since MATLAB deallocates the memory automatically. To do so you have to use the 'mexMakeArrayPersistent' function to use the pointer before it is deallocated automatically. The user can destroy it using the 'mxDestroyArray' function.