User`s manual

2 Creating C Language MEX-Files
2-38
Memory Management
Memory management within MEX-files is not unlike memory management for
regular C or Fortran applications. However, there are special considerations
because the MEX-file must exist within the context of a larger application, i.e.,
MATLAB itself.
Automatic Cleanup of Temporary Arrays
When a MEX-file returns to MATLAB, it gives to MATLAB the results of its
computations in the form of the left-hand side arguments – the
mxArrays
contained within the
plhs[] list. Any mxArrays created by the MEX-file that
are not in this list are automatically destroyed. In addition, any memory
allocated with
mxCalloc, mxMalloc, or mxRealloc during the MEX-file’s
execution is automatically freed.
In general, we recommend that MEX-files destroy their own temporary arrays
and free their own dynamically allocated memory. It is more efficient for the
MEX-file to perform this cleanup than to rely on the automatic mechanism.
However, there are several circumstances in which the MEX-file will not reach
its normal return statement. The normal return will not be reached if:
A call to
mexErrMsgTxt occurs.
A call to
mexCallMATLAB occurs and the function being called creates an
error. (A MEX-file can trap such errors by using
mexSetTrapFlag, but not all
MEX-files would necessarily need to trap errors.)
The user interrupts the MEX-file’s execution using
Ctrl-C.
The MEX-file runs out of memory. When this happens, MATLAB’s
out-of-memory handler will immediately terminate the MEX-file.
A careful MEX-file programmer can ensure safe cleanup of all temporary
arrays and memory before returning in the first two cases, but not in the last
two cases. In the last two cases, the automatic cleanup mechanism is necessary
to prevent memory leaks.
Persistent Arrays
You can exempt an array, or a piece of memory, from MATLAB’s automatic
cleanup by calling
mexMakeArrayPersistent or mexMakeMemoryPersistent.
However, if a MEX-file creates such persistent objects, there is a danger that a
memory leak could occur if the MEX-file is cleared before the persistent object
is properly destroyed. In order to prevent this from happening, a MEX-file that