MATLAB Application Program Interface | Search  Help Desk |
mxMalloc | Examples See Also |
Allocate dynamic memory using MATLAB's memory manager
#include "matrix.h" #include <stdlib.h> void *mxMalloc(size_t n);n
mxMalloc
returns NULL
. If unsuccessful in a MEX-file, the MEX-file terminates and control returns to the MATLAB prompt.
mxMalloc
is unsuccessful when there is insufficient free heap space.
MATLAB applications should always call mxMalloc
rather than malloc
to allocate memory. Note that mxMalloc
works differently in MEX-files than in stand-alone MATLAB applications.
In MEX-files, mxMalloc
automatically
n
bytes.
mxMalloc
. The MATLAB memory management facility automatically frees (deallocates) all of a MEX-file's parcels when control returns to the MATLAB prompt.
In stand-alone MATLAB applications, mxMalloc
defaults to calling the ANSI C malloc
function. If this default behavior is unacceptable, you can write your own memory allocation routine, and then register this routine with mxSetAllocFcns
. Then, whenever mxMalloc
is called, mxMalloc
calls your memory allocation routine instead of malloc
.
By default, in a MEX-file, mxMalloc
generates nonpersistent mxMalloc
data. In other words, the memory management facility automatically deallocates the memory as soon as the MEX-file ends. If you want the memory to persist after the MEX-file completes, call mexMakeMemoryPersistent
after calling mxMalloc
. If you write a MEX-file with persistent memory, be sure to register a mexAtExit
function to free allocated memory in the event your MEX-file is cleared.
When you finish using the memory allocated by mxMalloc
, call mxFree
. mxFree
deallocates the memory.
This example uses mxMalloc
to allocate enough heap space to hold a string.
void mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[]) { char *buf; int buflen; int status; if (mxIsString(prhs[0])) { /* Find out how long the input string array is. */ buflen = mxGetN(prhs[0])+1; /* Allocate enough memory to hold the converted string. */ buf = mxMalloc(buflen); /* Copy the string data into buf. */ status = mxGetString(prhs[0], buf, buflen); /* Manipulate the string.*/ ... /* When finished using the string, deallocate it. */ mxFree(buf); } else mexErrMsgTxt("Input argument must be a string.");For an additional example, see
mxmalloc.c
in the mx
subdirectory of the examples
directory.
mxCalloc
, mxFree
, mxDestroyArray
, mexMakeArrayPersistent
,mexMakeMemoryPersistent
, mxSetAllocFcns