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.
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.
Let's say I have a simple model with a C-Mex 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:
In a large model this could overwrite the output of another block, causing silent wrong results.
One of the first thing I do when I receive models with inexplicable behavior, I look for s-functions using find_system:
If there is an S-Function, I go to the Data Validity Diagnostics section of the model configuration:
and I set the Array Bounds Exceeded diagnostic to Error.
When simulating the model, I immediately get an error explaining that the output port signal pointer has been incremented outside allotted limits.
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.
댓글을 남기려면 링크 를 클릭하여 MathWorks 계정에 로그인하거나 계정을 새로 만드십시오.