Example: Generate Standalone C Code That Detects and Reports Run-Time Errors
This example shows how to generate C libraries or executables that detect and report run-time errors such as out-of-bounds array indexing. If the generated C code detects an error, it reports a message and terminates the program. This allows you to detect and fix errors that occur only on the target hardware.
Write the function getelement
that indexes into one structure field using
the value of the other structure
field.
function y = getelement(S) %#codegen y = S.A(S.u); end
Create a code configuration object for a standalone library or executable. For example, create a code configuration object for a static library. Enable the code generation report.
cfg = coder.config('lib');
cfg.GenerateReport = true;
Enable generation of run-time error detection and reporting.
cfg.RuntimeChecks = true;
Define an example input that you can use to specify the properties of the input argument.
S.A = ones(2,2); S.u = 1;
Generate code.
codegen -config cfg getelement -args {S}
To open the code generation report, click the View report link.
In the list of generated files, click getelement.c
.
You can see the code that checks for an error and calls a function to report the
error. For example, if the code detects an out-of-bounds array indexing error, it calls
rtDynamicBoundsError
to report the error and terminate the
program.
/* Include files */ #include "getelement.h" #include "getelement_rtwutil.h" #include <math.h> #include <stdio.h> #include <stdlib.h> /* Variable Definitions */ static rtBoundsCheckInfo emlrtBCI = { 1,/* iFirst */ 4, /* iLast */ 2, /* lineNo */ 5, /* colNo */ "S.A", /* aName */ "getelement", /* fName */ "C:\\Users\\username\\Documents\\MATLAB\\runtime-error-ex\\getelement.m",/* pName */ 0 /* checkKind */ }; static rtDoubleCheckInfo emlrtDCI = { 2,/* lineNo */ 5, /* colNo */ "getelement", /* fName */ "C:\\Users\\username\\Documents\\MATLAB\\runtime-error-ex\\getelement.m",/* pName */ 1 /* checkKind */ }; /* Function Definitions */ double getelement(const struct0_T *S) { int i; if (S->u != (int)floor(S->u)) { rtIntegerError(S->u, &emlrtDCI); } i = (int)S->u; if ((i < 1) || (i > 4)) { rtDynamicBoundsError(i, 1, 4, &emlrtBCI); } return S->A[i - 1]; }
The error reporting software uses fprintf
to write error messages
to stderr
. It uses abort
to terminate the
application. If fprintf
and abort
are not available,
you must provide them. The abort
function abruptly terminates the
program. If your system supports signals, you can catch the abort signal
(SIGABRT
) so that you can control the program termination.