This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English verison of the page.

Note: This page has been translated by MathWorks. Please click here
To view all translated materals including this page, select Japan from the country navigator on the bottom of this page.

mxMalloc (C and Fortran)

Allocate uninitialized dynamic memory using MATLAB memory manager

C Syntax

#include "matrix.h"
#include <stdlib.h>
void *mxMalloc(mwSize n);

Fortran Syntax

mwPointer mxMalloc(n)
mwSize n



Number of bytes to allocate for n greater than 0


Pointer to the start of the allocated dynamic memory, if successful. If unsuccessful in a MAT or engine standalone application, mxMalloc returns NULL in C (0 in Fortran). 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.

If you call mxMalloc in C with value n = 0, MATLAB returns either NULL or a valid pointer.


mxMalloc allocates contiguous heap space sufficient to hold n bytes. To allocate memory in MATLAB applications, use mxMalloc instead of the ANSI® C malloc function.

In MEX files, but not MAT or engine applications, mxMalloc registers the allocated memory with the MATLAB memory manager. When control returns to the MATLAB prompt, the memory manager then automatically frees, or deallocates, this memory.

How you manage the memory created by this function depends on the purpose of the data assigned to it. If you assign it to an output argument in plhs[] using the mxSetPr function, MATLAB is responsible for freeing the memory.

If you use the data internally, the MATLAB memory manager maintains a list of all memory allocated by the function and automatically frees (deallocates) the memory when control returns to the MATLAB prompt. In general, we recommend that MEX file functions destroy their own temporary arrays and free their own dynamically allocated memory. It is more efficient to perform this cleanup in the source MEX file than to rely on the automatic mechanism. Therefore, when you finish using the memory allocated by this function, call mxFree to deallocate the memory.

If you do not assign this data to an output argument, and you want it to persist after the MEX file completes, call mexMakeMemoryPersistent after calling this function. 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.


See the following examples in matlabroot/extern/examples/mx.

See the following examples in matlabroot/extern/examples/refbook.

Introduced before R2006a

Was this topic helpful?