| Products & Services | Industries | Academia | Support | User Community | Company |
| Download Product Updates | | | Get Pricing | | | Trial Software |
| Documentation → MATLAB |
| Contents | Index |
| Learn more about MATLAB |
#include "matrix.h" void mxFree(void *ptr);
mxFree(ptr) mwPointer ptr
mxFree deallocates heap space using the MATLAB memory management facility. This ensures correct memory management in error and abort (Ctrl+C) conditions.
To deallocate heap space, MATLAB applications in C should always call mxFree rather than the ANSI C free function.
The memory management facility maintains a list of all memory allocated by mxCalloc, mxMalloc, and mxRealloc. The memory management facility automatically deallocates all of a MEX-file's managed parcels when the MEX-file completes and control returns to the MATLAB prompt.
When mxFree appears in a stand alone MATLAB application, mxFree simply deallocates the contiguous heap space that begins at address ptr. In a MEX-file, mxFree also removes the memory parcel from the memory management facility's list of memory parcels.
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, mxMalloc, and mxRealloc are nonpersistent. The 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 good programming practice to deallocate memory as soon as you are through using it. Doing so generally makes the entire system run more efficiently.
If an application calls mexMakeMemoryPersistent, the specified memory parcel becomes persistent. When a MEX-file completes, the 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 cleanup handler. The cleanup handler calls mxFree.
See mxcalcsinglesubscript.c in the matlabroot/extern/examples/mx folder .
Additional examples:
phonebook.c in the matlabroot/extern/examples/refbook folder
explore.c and mexatexit.c in the matlabroot/extern/examples/mex folder
mxcreatecharmatrixfromstr.c, mxisfinite.c, mxmalloc.c, and mxsetdimensions.c in the matlabroot/extern/examples/mx folder
mexAtExit, mexMakeArrayPersistent, mexMakeMemoryPersistent, mxCalloc, mxDestroyArray, mxMalloc, mxRealloc
![]() | mxDuplicateArray (C and Fortran) | mxGetCell (C and Fortran) | ![]() |

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.
| © 1984-2009- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |