Main Content

Persistent mxArrays

You can exempt an array, or a piece of memory, from the MATLAB® automatic cleanup by calling mexMakeArrayPersistent or mexMakeMemoryPersistent. However, if a MEX function creates persistent objects, then a memory leak could occur if the MEX function is cleared before the persistent object is properly destroyed. To prevent memory leaks, use the mexAtExit function to register a function to free the memory for objects created using these functions.

The following MEX file code creates a persistent array and properly disposes of it.

#include "mex.h"

static int initialized = 0;
static mxArray *persistent_array_ptr = NULL;

void cleanup(void) {
    mexPrintf("MEX file is terminating, destroying array\n");

void mexFunction(int nlhs,
    mxArray *plhs[],
    int nrhs,
    const mxArray *prhs[])
  if (!initialized) {
    mexPrintf("MEX file initializing, creating array\n");
    /* Create persistent array and register its cleanup. */
    persistent_array_ptr = mxCreateDoubleMatrix(1, 1, mxREAL);
    initialized = 1;

    /* Set the data of the array to some interesting value. */
    *mxGetDoubles(persistent_array_ptr) = 1.0;
  } else {
    mexPrintf("MEX file executing; value of first array element is %g\n",

See Also


Related Topics