MATLAB: Safe memory management when interfacing code via MEX

external interfacesmexmexlockmxmalloc

I am using MEX to interface to C/C++ code, which includes the creation of objects that will outlive the call to the MEX-function. These objects will eventually be deallocated by subsequent calls to the MEX function. That is, there is persistent memory in the MEX-function.
If I understand things right, I can increase a lock counter using mexLock whenever memory is allocated in my wrappers using either C "malloc" or C++ "new" and then decrease the lock counter using mexUnlock whenever I free objects using C "free" or C++ "delete". That will prevent the MEX function to be released while the function is still in use.
Is this safe usage? I have read that one should always use mxMalloc/mxFree instead of malloc/free, but when interfacing code, this is not an option.

Best Answer

Locking the mex file is only needed to preserve static data. Any memory allocated using malloc or new will persist until deleted or matlab exits even if your mex file is unloaded and reloaded.
Use of mxMalloc is only* need to prevent leaks in c (or c style) code that throws exceptions via mexErrMsgIdAndTxt ether directly or indirectly.
*The other not recommended need is when the pointer will be passed to mxSetData or related functions.