MATLAB: C S-function problem when trying to get a pointer to a structure

c s-functionspointerpwork vectorssimulink

Hello all,
I created a structure within the mdlStart method and a pointer to it as follows:
SomeStructureType myStruct;
SomeStructureType* myStruct_ptr;
myStruct_ptr = &myStruct;
Then I saved the pointer into a (previously defined) PWork vector:
ssSetPWorkValue(S, 0, (void *)myStruct_ptr);
When I retrieve the pointer, within mdlStart, as follows:
anotherStruct_ptr= (SomeStructureType*)ssGetPWorkValue(S,0);
everything works fine. anotherStruct_ptr points to myStruct. But when I try to get the same pointer from the mdlTerminate method, I obtain a wrong one:
SomeStructureType *Test_ptr;
Test_ptr = (SomeStructureType*)ssGetPWorkValue(S,0);
Test_ptr does not point to myStruct.
Avoiding the cast gives the same result. I also tried to use ssSetUserData and ssGetUserData instead of ssSetPWorkValue and ssGetPWorkValue, respectively, but the result is still wrong.
I already used PWork vectors without any problem, but this is the first time I use it to hold a pointer to a structure. Am I doing something wrong?

Best Answer

You need to use:
SomeStructureType* myStruct_ptr = new SomeStructureType;
to create the pointer. If you simply assign it to a variable on the stack, that memory is free'd at the end of mdlStart, and any further references to it are pointing to corrupt memory and can cause a segmentation violation.
Also, remember to use delete to free that memory in mdlTerminate.