a MEX-file returns control to MATLAB®, it returns the results
of its computations in the output arguments—the
contained in the left-side arguments
plhs. MATLAB destroys
mxArray created by the MEX-file that is not
in this argument list. In addition, MATLAB frees any memory that
was allocated in the MEX-file 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-file 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 the sections Memory Management in Creating C/C++ Language MEX-Files and Memory Management Issues.