Main Content

C Compiler Considerations for Signed Integer Overflows

The code generator reduces memory usage and enhances performance of code that it produces by assuming that signed integer C operations wrap on overflow. A signed integer overflow occurs when the result of an arithmetic operation is outside the range of values that the output data type can represent. The C programming language does not define the results of such operations. Some C compilers aggressively optimize signed operations for in-range values at the expense of overflow conditions. Other compilers preserve the full wrap-on-overflow behavior. For example, the gcc and MinGW compilers provide an option to reliably wrap overflow on signed integer overflows.

When you generate code, if you use a supported compiler with the default options configured by the code generator, the compiler preserves the full wrap-on-overflow behavior. If you change the compiler options or compile the code in another development environment, it is possible that the compiler does not preserve the full wrap-on-overflow behavior. In this case, the executable program can produce unpredictable results.

If this issue is a concern for your application, consider one or more of the following actions:

  • Verify that the compiled code produces the expected results.

  • If your compiler has an option to force wrapping behavior, turn it on. For example, for the gcc compiler or a compiler based on gcc, such as MinGW, configure the build process to use the compiler option -fwrapv.

  • Choose a compiler that wraps on integer overflow.

  • If you have Embedded Coder installed, develop and apply a custom code replacement library to replace code generated for signed integers. For more information, see Code Replacement Customization (Embedded Coder).

Related Topics