S-Function PWork pointers and memory allocation error

I am developing an interface between simulink and a custom c++ library using an S-Function. The purpose of my library is to solve the state of a cable at different stages when forces are applied to each end. A cable object is initialised in the mdlStart section. I set the PWork value to a pointer to this. When I dereference the PWork pointer in the Output section I am getting a Memory Allocation Error.

My code looks like this:

static void mdlStart(SimStruct *S)
{
  Line line = builder.initialise(start,end,reel_out_length,9.81,1.225);
  cout << line.node_positions() << endl; // outputs the correct positions of the line
  ssSetPWorkValue(S, 0, &line);
  Line *l = static_cast<Line *>(ssGetPWork(S)[0]);
  cout << l->node_positions() << endl; // outputs the correct positions of the line
}
static void mdlOutputs(SimStruct *S, int_T tid)
{
  Line *l = static_cast<Line *>(ssGetPWork(S)[0]);
  cout << l->node_positions() << endl; // causes memory allocation error  
}

The mdlStart function runs well, but the mdlOutputs function gives me this error:

An error occurred while running the simulation and the simulation was terminated
Caused by:
Memory allocation error. 

I am relatively new to both C++ and Simulink so there may be something obvious I am missing. Any help is greatly appreciated.

 Accepted Answer

The object I was trying to access was being created on the stack and not on the heap. Sorted now.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!