Main Content

Memory Allocation

When you create an S-function, you might need to allocate memory for each instance of your S-function. The standard MATLAB® API memory allocation routines mxCalloc and mxFree should not be used with C MEX S-functions, because these routines are designed to be used with MEX files that are called from the MATLAB environment and not the Simulink® environment. The correct approach for allocating memory is to use the stdlib.h library routines calloc and free. In mdlStart, allocate and initialize the memory

UD *ptr = (UD *)calloc(1,sizeof(UD));

where UD, in this example, is a data structure defined at the beginning of the S-function. Then, place the pointer to it either in the pointer work vector

ssSetPWorkValue(S, 0, ptr);

or attach it as user data.

ssSetUserData(S,ptr); 

In mdlTerminate, free the allocated memory. For example, if the pointer was stored in the user data

UD *ptr = ssGetUserData(S);
free(ptr);