Main Content

mdlTerminate

Perform any actions required at termination of the simulation

Required

Yes

Languages

C, C++

Syntax

void mdlTerminate(SimStruct *S)

Arguments

S

SimStruct representing an S-Function block.

Description

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). This method is called at the end of every simulation in Fast Restart mode.

In C MEX S-functions, the mdlTerminate method is called after a simulation (mdlStart is called).

In addition, if the SS_OPTION_CALL_TERMINATE_ON_EXIT option is set for a given S-function, and if mdlInitializeSizes is called, then the user is guaranteed that Simulink will call mdlTerminate. One reason to set the SS_OPTION_CALL_TERMINATE_ON_EXIT option is to allocate memory in mdlInitializeSizes rather than wait until mdlStart.

Note that Simulink® calls mdlInitializeSizes under a number of circumstances, including compilation and simulation. Simulink will also call mdlInitializeSizes during model editing if you perform an operation such as the setting of parameters.

In C MEX S-functions, use the UNUSED_ARG macro if the mdlTerminate function does not perform any actions that require the SimStruct S to indicate that the S input argument is required, but not used in the body of the callback. To do this, insert the line

UNUSED_ARG(S)

after any declarations in mdlTerminate.

Note

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 mdlTerminate(SimStruct *S) 
{ 
   /* Add mdlTerminate code here *
} 
#endif 

The define statement makes the mdlTerminate 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.

Examples

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

{
  int i;
  for (i = 0; i<ssGetNumPWork(S); i++) {
    if (ssGetPWorkValue(S,i) != NULL) {
      free(ssGetPWorkValue(S,i));
    }
  }
}

Version History

Introduced before R2006a