MATLAB: What is the appropriate function to free memory when using MATLAB Engine API

MATLAB

In MATLAB 7.3 (R2006b), the documentation for the MATLAB Engine API function "engGetVariable" reads:
engGetVariable reads the named mxArray from the MATLAB engine session associated with ep and returns a pointer to a newly allocated mxArray structure, or NULL if the attempt fails. engGetVariable fails if the named variable does not exist. Be careful in your code to free the mxArray created by this routine when you are finished with it.
The last line, in saying "free the mxArray", suggests to use "mxFree". More often, the proper way to free the memory is with "mxDestroyArray".

Best Answer

mxDestroyArray is used to free dynamic memory allocated by mxCreate. This applies to any time you create an mxArray, such as with most of the mxArray API functions (mxCreateDoubleMatrix, mxCreateCellMatrix, etc). This also applies to engGetVariable, because engGetVariable returns a pointer to a newly allocated mxArray. mxDestroyArray should be called to free that dynamic memory when finished.
mxFree is used to free dynamic memory allocated by mxCalloc, mxMalloc, or mxRealloc (similar to their malloc counterpart, except they use the MATLAB memory manager). Calls to mxFree are less common.