MATLAB Application Program Interface | Search  Help Desk |
mxFree | Examples See Also |
Free dynamic memory allocated by mxCalloc
#include "matrix.h" void mxFree(void *ptr);ptr
mxCalloc
.
To deallocate heap space, MATLAB applications should always call mxFree
rather than the ANSI C free
function.
mxFree
works differently in MEX-files than in stand-alone MATLAB applications.
In MEX-files, mxFree
aut
omatically
free
function, which deallocates the contiguous heap space that begins at address ptr
.
mxCalloc
(and by the mxCreate
calls). The MATLAB memory management facility automatically frees (deallocates) all of a MEX-file's parcels when control returns to the MATLAB prompt.
By default, when mxFree
appears in stand-alone MATLAB applications, mxFree
simply calls the ANSI C free
function. If this default behavior is unacceptable, you can write your own memory deallocation routine and register this routine with mxSetAllocFcns
. Then, whenever mxFree
is called, mxFree
calls your memory allocation routine instead of free
.
In a MEX-file, your use of mxFree
depends on whether the specified memory parcel is persistent or nonpersistent. By default, memory parcels created by mxCalloc
are nonpersistent. However, if an application calls mexMakeMemoryPersistent
, then the specified memory parcel becomes persistent.
The MATLAB memory management facility automatically frees all nonpersistent memory whenever a MEX-file completes. Thus, even if you do not call mxFree
, MATLAB takes care of freeing the memory for you. Nevertheless, it is a good programming practice to deallocate memory just as soon as you are through using it. Doing so generally makes the entire system run more efficiently.
When a MEX-file completes, the MATLAB memory management facility does not free persistent memory parcels. Therefore, the only way to free a persistent memory parcel is to call mxFree
. Typically, MEX-files call mexAtExit
to register a clean-up handler. Then, the clean-up handler calls mxFree
.
See the examples on the mxCalloc
and mexAtExit
reference pages.
mxCalloc
, mxDestroyArray
, mxMalloc
, mexMakeArrayPersistent
, mexMakeMemoryPersistent