Automatic Cleanup of Temporary Arrays in MEX Files
When a MEX function returns control to MATLAB®, it returns the results of its computations in the output arguments—the
mxArray
s contained in the left-side arguments plhs[]
.
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
mxCalloc
, mxMalloc
, or
mxRealloc
functions.
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. However, there are several circumstances in which the MEX function does not reach its normal return statement.
The normal return is not reached if:
MATLAB calls
mexCallMATLAB
and the function being called creates an error. (A source MEX file can trap such errors by using themexCallMATLABWithTrap
function, but not all MEX files necessarily need to trap errors.)The user interrupts the MEX function execution using Ctrl+C.
The MEX function runs out of memory. The MATLAB out-of-memory handler terminates the MEX function.
In the first case, a MEX programmer can ensure safe cleanup of temporary arrays and memory before returning, but not in the last two cases. The automatic cleanup mechanism is necessary to prevent memory leaks in those cases.
You must use the MATLAB-provided functions, such as mxCalloc
and
mxFree
, to manage memory. Do not use the standard C library
counterparts; doing so can produce unexpected results, including program
termination.
Example
This example shows how to allocate memory for variables in a MEX function. For
example, if the first input to your function (prhs[0]
) is a
string, to manipulate the string, create a buffer buf
of size
buflen
. The following statements declare these
variables:
char *buf; int buflen;
The size of the buffer depends the number of dimensions of your input array and
the size of the data in the array. This statement calculates the size of
buflen
:
buflen = mxGetN(prhs[0])*sizeof(mxChar)+1;
Next, allocate memory for buf
:
buf = mxMalloc(buflen);
At the end of the program, if you do not return buf
as a
plhs
output parameter, then free its memory as
follows:
mxFree(buf);
Before exiting the MEX function, destroy temporary arrays and free dynamically
allocated memory, except if such an mxArray
is returned in the
output argument list, returned by mexGetVariablePtr
, or used to
create a structure. Also, never delete input arguments.
Use mxFree
to free memory allocated by the
mxCalloc
, mxMalloc
, or
mxRealloc
functions. Use
mxDestroyArray
to free memory allocated by the
mxCreate*
functions.