Simulink crash after free(ptr) in mdlTerminate and pointers strange behavior.

1 回表示 (過去 30 日間)
Nicola Blasuttigh
Nicola Blasuttigh 2020 年 9 月 2 日
Hi everyone!
I have a problem with a S-function that I'm using with Simulink.
Inside mdlStart I used malloc() to allocate memory in this way.
static void mdlStart(SimStruct *S)
{
char *str = (char*)malloc(INPUT_SIZE+1);
char *cut_str = (char*)malloc(INPUT_SIZE+1);
if (str==NULL)
{
std::cout << "Memory problem!\n";
}
else if (cut_str==NULL)
{
std::cout << "Memory problem!\n";
}
else
{
ssSetUserData(S,str);
ssSetUserData(S,cut_str);
}
}
First question: is it ok?
Then, inside mdlOutputs I read the input vector and I stored it inside char *str.
static void mdlOutputs(SimStruct *S, int_T tid)
{
InputPtrsType u = ssGetInputPortSignalPtrs(S,0);
InputUInt8PtrsType resp8 = (InputUInt8PtrsType)u;
real_T *y0 = (real_T *) ssGetOutputPortRealSignal(S, 0);
char* str = (char *)ssGetUserData(S);
char* cut_str = (char *)ssGetUserData(S);
for ( int i=0; i<INPUT_SIZE; i++ )
{
str[i]=*resp8[i]; // Copy the resp8 vector inside *str.
}
str[INPUT_SIZE]='\0'; // Null-terminated char
for (int i=0; i<OUTPUT_SIZE;i++)
{
y0[i]=cut_str[i]; // ??? This shows me the same values of str.
}
}
Now, str stores the resp8 values and if I output this values are ok.
The problem is that if I output the values of cut_str (that I did no touch after mdlStart!!!) show me the same valus of str! How is possible??
Another problem is related to mdlTerminate when I try to free the memory!
static void mdlTerminate(SimStruct *S)
{
char* str = (char *)ssGetUserData(S);
char* cut_str = (char *)ssGetUserData(S);
if (str!=NULL)
{
free(str);
std::cout << "str memory free" ;
}
if (cut_str!=NULL)
{
free(cut_str);
std::cout << "cut_str memory free!" ;
}
}
During this last phase, Simulink stucks at 100% and after a few seconds it closes unexpectedly. (both Matlab and Simulink)
No errors, no warnings, no dialog box: nothing.
What am I doing wrong?
Thanks!

回答 (0 件)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by