When a MEX function returns control to MATLAB®, it returns the results of its computations in the output arguments—the
mxArrays contained in the left-side arguments
These arrays must have a temporary scope, so do not pass arrays created with the
mexMakeArrayPersistent function in
plhs. MATLAB destroys any
mxArray created by the MEX function that is not in
plhs. MATLAB also frees any memory that was allocated in the MEX function using the
Any misconstructed arrays left over at the end of a binary MEX file execution have the potential to cause memory errors.
MathWorks® recommends that MEX functions destroy their own temporary arrays and free their own dynamically allocated memory. It is more efficient to perform this cleanup in the source MEX file than to rely on the automatic mechanism. For more information on memory management techniques, see Memory Management Issues.