Using the C++ Math Library    

Setting Up Your Own Memory Management Routines

Because this default memory management may not be appropriate for all applications, we provide the function mwSetLibraryAllocFcns() that you can use to register your own memory management routines:

The types defined for the arguments to mwSetLibraryAllocFcns() are:

To set up your own memory management routines, you need to write four routines: two memory allocation routines, one memory reallocation routine, and one deallocation routine. You then call mwSetLibraryAllocFcns() to register those routines with the library.

For example, this call registers the standard C++ memory management routines with the MATLAB C++ Math Library. (Note, however, that using the standard C++ memory management routines will decrease the performance of the MATLAB C++ Math Library.)

Calloc Allocation Routine

Any memory calloc routine that you write must conform to the type:

The calloc function allocates a block of memory based on the number of contiguous elements that you want allocated (its first argument) and an integer representing the size of each element (its second argument). The routine initializes the allocated memory to zero.

Deallocation Routine

If you write a memory allocation routine, you must write a corresponding routine that frees memory. Any memory free routine that you write must conform to this type:

The free function takes a pointer to the beginning of the memory block to be freed and returns void.

The overloaded delete operator in mwArray calls this function, as does mxFree().

Reallocation Routine

Any memory reallocation routine that you write must conform to this type:

The realloc function takes a pointer to the beginning of the memory block to reallocate and an integer size of each element. It returns a pointer to void.

Malloc Allocation Routine

Any memory allocation routine that you write must conform to this type:

The malloc function takes an integer size that represents the number of bytes to allocate and returns a pointer to void. Unlike calloc, malloc does not initialize the memory it returns.

The overloaded new operator in mwArray calls this function, as do the mx-prefixed allocation routines, for example, mxMalloc().


 Memory Management Performance and Efficiency