This is machine translation

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

Note: This page has been translated by MathWorks. Click here to see
To view all translated materials including this page, select Country from the country navigator on the bottom of this page.


Perform any actions required once at termination of the simulation




C, C++


void mdlCleanupRuntimeResources(SimStruct *S)



SimStruct representing an S-Function block.


This method performs any actions, such as freeing of memory, that must be performed when the simulation is terminated or when an S-Function block is destroyed (e.g., when it is deleted from a model).

In C MEX S-functions, the mdlCleanupRuntimeResources method is called after a simulation (mdlSetupRuntimeResources is called), and it reverses the actions performed by mdlSetupRuntimeResources.


If you have Simulink® Coder™, when generating code for a noninlined C MEX S-function that contains this method, make sure the method is not wrapped in a #if defined(MATLAB_MEX_FILE) statement. For example:

#if defined(MATLAB_MEX_FILE) 
static void mdlCleanupRuntimeResources(SimStruct *S) 
   /* Add mdlCleanupRuntimeResources code here *

The define statement makes the mdlCleanupRuntimeResources method available only to a MATLAB® MEX file. If the S-function is not inlined, Simulink Coder cannot use this method, resulting in link or run-time errors.


Suppose your S-function allocates blocks of memory in mdlSetupRuntimeResources and saves pointers to the blocks in a PWork vector. The following code fragment would free this memory.

static void mdlCleanupRuntimeResources(SimStruct *S)
  int i;
  for (i = 0; i<ssGetNumPWork(S); i++) {
    if (ssGetPWorkValue(S,i) != NULL) {

Introduced in R2016b