User`s manual
1 Calling C and Fortran Programs from MATLAB
1-40
Creating a Temporary mxArray with Improper Data
You cannot call mxDestroyArray on an mxArray whose data was not allocated
by an API routine.
Warning
Warning: You have attempted to point the data of an array to a
block of memory not allocated through the MATLAB API. MATLAB will
attempt to fix the problem and continue, but this will result in
memory faults in future releases.
Example That Causes Warning
If you call mxSetPr, mxSetPi, mxSetData, or mxSetImagData, specifying memory
that was not allocated by
mxCalloc, mxMalloc, or mxRealloc as the intended
data block (second argument), then when the MEX-file returns, MATLAB will
attempt to free the pointer to real data and the pointer to imaginary data (if
any). Thus MATLAB will attempt to free memory, in this example, from the
program stack. This will cause the above warning when MATLAB attempts to
reconcile its consistency checking information.
mxArray *temp = mxCreateDoubleMatrix(0,0,mxREAL);
double data[5] = {1,2,3,4,5};
...
mxSetM(temp,1); mxSetN(temp,5); mxSetPr(temp, data);
/* INCORRECT */
Solution
Rather than use mxSetPr to set the data pointer, instead create the mxArray
with the right size and use
memcpy to copy the stack data into the buffer
returned by
mxGetPr.
mxArray *temp = mxCreateDoubleMatrix(1,5,mxREAL);
double data[5] = {1,2,3,4,5};
...
memcpy(mxGetPr(temp), data, 5*sizeof(double)); /* CORRECT */
Potential Memory Leaks
Prior to Version 5.2, if you created an mxArray using one of the API creation
routines and then you overwrote the pointer to the data using
mxSetPr,
MATLAB would still free the original memory. This is no longer the case.