Monday, May 16, 2022

Dangers of C++

Recently I had a strange bug that caused a previously working C++ simulation to fail. It turned out that a logically unrelated portion of code was corrupting the memory and that corruption resulted in changing of parameter values which resulted in instability. Corruption was due to writing out of index. If that index pointed to a memory location outside the boundaries of my program I would get an access violation. Unfortunately, indices were pointing to my programs memory, therefore I did not get any errors from the operating system and had to pin point the bug by trial and error, i.e. commenting out sections of code until I got a stable state and then uncommenting until I got instability. A simplified version of the code:

Friday, May 13, 2022

Simulink: Generating code without model version and date

When you generate code with Simulink, the generated header and source files will have model version and date in code comments. This results in version changes in your version control system even when you have not changed any logic. In order to avoid unnecessary version updates, you should comment out the "Model version" and "C/C++ source code generated on" sections in the ert_code_template.cgt file (Configuration Parameters > Code Generation > Templates > Code Templates).

Dangerous while loop

Today a program I am writing stopped responding. After some debugging effort, I came across a 3rd party function that limited an input angle to the [-180, 180] degrees interval. It was using a while loop to increment or decrement the angle. Unfortunately, I was passing an uninitialized variable to it and its value was -9.2...e+61. Such a large value would take years for the function to limit. Below is the original function constrainAngleWhile(), together with much better alternatives: