mxCalloc, mxFree

Purpose

Allocate and free memory using MATLAB's memory manager.

C Synopsis

void *mxCalloc(n,size)
  unsigned int n;
  unsigned int size;
void mxFree(ptr)
  void *ptr;

Fortran Synopsis

integer*4 function mxCalloc(n,size)
subroutine mxFree(ptr)
integer*4 ptr, n, size

Arguments

n
number of elements
ptr
pointer to allocated memory
size
number of bytes per element

Description

These routines provide the basic memory allocation facilities for MEX-files. Except in rare circumstances, use mxCalloc and mxFree, rather than calloc, malloc, and free, to allocate memory. mxCalloc and mxFree in the libmex library allocate and free memory using MATLAB's own memory management facility. This ensures correct memory management in error and abort (Ctrl-C) conditions.

mxCalloc allocates memory on the MATLAB heap and sets it all to zeros. This function is useful for creating temporary work arrays. On return from your MEX-file, MATLAB automatically frees any memory that you allocated with mxCalloc. If you do not want it freed automatically, use calloc or malloc instead.

mxFree returns to the heap any memory allocated using mxCalloc. If you do not free memory with this command, MATLAB frees it automatically on return from the MEX-file.

calloc and malloc also allocate memory on the system's heap. They differ from mxCalloc in that they use the system calloc and malloc linked into MATLAB, rather than using MATLAB's own memory managed allocation routines. Use calloc and malloc to allocate memory that you want to persist between calls to the MEX-file.

malloc, calloc, and free use call-backs to the run-time library routines by the same names that are linked into the MATLAB image. The cmex command does not link in new versions from the run-time library.

malloc allocates uninitialized memory, whereas calloc initializes it to all zeros.

Use free to return memory that was allocated using malloc and calloc.

If you write a MEX-file with persistent memory (uses calloc or malloc to allocate memory and doesn't free it between calls to the MEX-file), be sure to register a mexAtExit function to free allocated memory in the event your MEX-file is cleared.

While mxCalloc and mxFree in the libmex library allocate and free memory using MATLAB's own memory management facility, mxCalloc and mxFree in the libmat library simply call calloc and free.

(c) Copyright 1994 by The MathWorks, Inc.