MATLAB: MexAtExit and static variables

memorymexstatic variables

I have a quick question regarding static variables in mex files. Basically it is not behaving as I expected. However I'm not a programmer so perhaps this is simply a silly error. I have the problem in a large mex file but the following snippit is enough to demonstrate the issue.
———————
#include stuff
static double *X = NULL;
static void clearX(void)
{
mexPrintf("Clearing X\n");
mxFree(X);
}
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
double *X2;
ptrdiff_t stride = 1, m;
m = (ptrdiff_t)mxGetM(prhs[0]);
if( X == NULL ){
mexPrintf("\tAllocating Memory for X.\n");
X = (double *) mxMalloc((size_t) m*sizeof(double));
mexAtExit(clearX);
}
X2 = mxGetPr(prhs[0]);
mexPrintf("\tCopying %f to X.\n",X2[0]);
mexPrintf("\tX was %f.\n",X[0]);
dcopy(&m,X2,&stride,X,&stride);
mexPrintf("\tX is now %f.\n",X[0]);
}
————————————–
This is then compiled
mex -g -O -largeArrayDims testMex.c -lmwblas
I then test it:
>> a=randn(1);testMex(a)
Allocating Memory for X.
Copying -0.271685 to X.
X was 0.000000.
X is now -0.271685.
>> a=randn(1);testMex(a)
Copying 0.604548 to X.
X was 0.000000.
X is now 0.604548.
So the question is, if X is not being freed (clearX is not being called) and its not being reallocated, why is X reset to 0.0?

Best Answer

You should consider declaring your persistent variable X as an mxArray, since you are using MATLAB-managed memory anyway. mxArrays can then be declared as persistent using mexMakeArrayPersistent, which ensures that MATLAB doesn't release that memory (I don't know if you can do that with built-in pointers allocated using mxMalloc). Please see Persistent Arrays for more information.