MATLAB: Is MATLAB /Simulink (R2009b) crashing during code generation but simulation works fine, with a model having Level 2 C S-function

MATLAB

I have a model with a Level 2 C S-function in it.
The simulation runs fine, but code generation fails. When working with S-function, MATLAB generates code even during simulation, hence why during code generation does it crashes.
There is no crash dump and it is a silent crash.

Best Answer

There can be extra section of S-function, which runs only during Code generation. This can be defined using MDL_RTW.
Furthermore, MATLAB was crashing because of freeing of incorrect memory inside the MDL_RTW section.
The errorneous code was :
#if defined (MATLAB_MEX_FILE) /* Is this file being compiled as a MEX-file? */
#define MDL_RTW
/* Function: mdlRTW ===========================================================
*/
static void mdlRTW(SimStruct *S)
{
boolean_T err = 0;
int_T status = mxGetNumberOfElements(STATUS_PARAM(S));
int_T index = mxGetNumberOfElements(INDEX_PARAM(S));
char_T *statusStr;
char_T *indexStr;
if ((statusStr=(char_T*)malloc(status)+1) == NULL ||
(indexStr=(char_T*)malloc((index*5)+2+1)) == NULL) {
ssSetErrorStatus(S,"Memory allocation error in mdlRTW");
return;
}
.... %extra lines of code
free(indexStr);
free(statusStr);
}
#endif /* MDL_RTW */
The issue is during the memory allocation call:
statusStr=(char_T*)malloc(status)+1
Ideally it should be (Corrected) :
statusStr=(char_T*)malloc(status+1)
Notice, the difference in where the paranthesis closes for MALLOC. In the errorneous code, freeing a incorrect address was leading to a silent crash.