Guy on Simulink

Simulink & Model-Based Design

Problems with your S-Functions… Try this Diagnostic!

Ahhh... C Mex S-function...

If you ever tried creating a C Mex S-function and were a little rusty on your C programming, you might have experienced strange behavior or event MATLAB crashes. This is possible... C Mex S-Functions let you do almost anything you can think of, including shooting yourself in the foot.

This week I want to highlight a diagnostic that saved me a lot of time when that happened to me: Array Bounds Exceeded.

The Problem

Every once in a while, I receive models with one or many of the following symptoms:

  • Sporadic, seemingly random, crashes resulting in a dialog saying MATLAB has encountered an internal problem and needs to close
  • Inexplicable wrong results for some signals
  • MATLAB crashes without any error, it just disappears
  • Different behavior on different machines (e.g. crash on machine A, wrong results on machine B, different wrong results on machine C, etc...)

S-functions with bugs in them can cause that type of behavior. To help debugging those issues, the Array Bounds Exceeded diagnostic can help.

Example

Let's say I have a simple model with a C-Mex S-Function:

Simple model using an s-function

For some reasons, a bug got introduced in my S-Function: a pointer is incremented beyond its range in memory. In this case, the output signal is a scalar, but my S-function writes to it as if it was a vector with two elements:

S-Function Code with a bug

In a large model this could overwrite the output of another block, causing silent wrong results.

Debugging

One of the first thing I do when I receive models with inexplicable behavior, I look for s-functions using find_system:

Searching for S-function

If there is an S-Function, I go to the Data Validity Diagnostics section of the model configuration:

Data Validity Diagnostics

and I set the Array Bounds Exceeded diagnostic to Error.

Array Bounds Exceeded Diagnostics

When simulating the model, I immediately get an error explaining that the output port signal pointer has been incremented outside allotted limits.

Array Bounds Exceeded Error Message

This gives me a very good idea of where to focus when I will attach a debugger and try to debug the s-function.

Now it's your turn

This diagnostic cannot catch 100% of the bugs in your s-functions, but it can help identifying a very common type of bug. I recommend using it carefully because it will add the overhead of checking array bounds after every call to your S-function, and slowdown your model.

Do you use the Array Bounds Exceeded diagnostic when creating S-Function? Let us know by leaving a comment here.

|
  • print

コメント

コメントを残すには、ここ をクリックして MathWorks アカウントにサインインするか新しい MathWorks アカウントを作成します。