Main Content

C Compiler Considerations for Signed Integer Overflows

The C programming language does not define the overflow behavior of an arithmetic operation when the result is outside the range of values for the output data type. 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. The code generator reduces memory usage and enhances performance of code that it produces by assuming that signed integer C operations wrap on overflow.

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