User`s manual

Troubleshooting
1-41
For example,
pr = mxCalloc(5*5, sizeof(double));
... <load data into pr>
plhs[0] = mxCreateDoubleMatrix(5,5,mxREAL);
mxSetPr(plhs[0], pr); /* INCORRECT */
will now leak 5*5*8 bytes of memory, where 8 bytes is the size of a double.
You can avoid that memory leak by changing the code
plhs[0] = mxCreateDoubleMatrix(5,5,mxREAL);
pr = mxGetPr(plhs[0]);
... <load data into pr>
or alternatively
pr = mxCalloc(5*5, sizeof(double));
... <load data into pr>
plhs[0] = mxCreateDoubleMatrix(5,5,mxREAL);
mxFree(mxGetPr(plhs[0]));
mxSetPr(plhs[0], pr);
Note that the first solution is more efficient.
Similar memory leaks can also occur when using
mxSetPi, mxSetData,
mxSetImagData, mxSetIr, or mxSetJc. You can address this issue as shown
above to avoid such memory leaks.
MEX-Files Should Destroy Their Own Temporary Arrays
In general, we recommend that MEX-files destroy their own temporary arrays
and clean up their own temporary memory. All
mxArrays except those returned
in the left-hand side list and those returned by
mexGetArrayPtr may be safely
destroyed. This approach is consistent with other MATLAB API applications
(i.e., MAT-file applications, engine applications, and MATLAB Compiler
generated applications, which do not have any automatic cleanup mechanism.)