HomeAbout UsContact Us

Fixing C Signed Integer Overflow With Checked Builtins

By Jithin Tom
Published in Embedded C/C++
December 01, 2026
8 min read
Fixing C Signed Integer Overflow With Checked Builtins

Table Of Contents

01
The Problem: Signed Overflow Is Undefined Behavior
02
The Solution: Builtin Checked Arithmetic
03
C23 Standardization: <stdckdint.h>
04
Real-World Patterns: Sensor Processing, PID, Checksums
05
Compiler Support and Feature Detection
06
Verification: Testing With UBSan
07
Migration Checklist
08
Summary
09
Related Reading
10
References
11
Frequently Asked Questions

Signed integer overflow is one of the most insidious sources of bugs in embedded C firmware. Code that passes every test at -O0 can silently misbehave at -O2 because the compiler exploits the undefined behavior assumption to optimize aggressively. A sensor scaling function that works in debug may return garbage in release; a bounds check that catches overflow at -O0 may be eliminated entirely at -O2. A PID controller that stabilizes a motor in debug builds may command full-scale output in release because an intermediate multiplication overflowed and saturation or clamping logic was optimized away.

This article shows how to fix signed integer overflow using GCC and Clang’s builtin checked arithmetic functions (__builtin_add_overflow, __builtin_sub_overflow, __builtin_mul_overflow) and the C23 <stdckdint.h> header. These tools evaluate the operation in infinite-precision signed arithmetic, store the truncated result without invoking undefined behavior, and detect overflow reliably at any optimization level. We cover the optimizer’s reasoning, practical migration patterns, real-world embedded examples, and verification strategies with UBSan.

The Problem: Signed Overflow Is Undefined Behavior

In C17 (ISO/IEC 9899:2018, Section 6.5, paragraph 5) — and retained in C23 (ISO/IEC 9899:2024, Section 6.5.1, paragraph 5) — an expression whose mathematical result is not in the range of representable values for its type invokes undefined behavior (UB). The standard imposes no requirements on the program once signed overflow occurs: the compiler may emit any code, including a binary that appears to wrap silently in debug builds yet produces broken control flow in release builds. This is not a theoretical quirk; it is a standard optimization strategy in GCC, Clang, and commercial compilers.

#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
int32_t scale_sensor(int32_t raw, int32_t factor) {
return raw * factor; // UB if mathematical product exceeds int32_t range
}
int main(void) {
int32_t result = scale_sensor(2000000000, 2); // 4,000,000,000 > INT32_MAX
printf("Result: %" PRId32 "\n", result);
return 0;
}

At -O0 on GCC targeting Cortex-M, the 32-bit MUL instruction happens to leave the low 32 bits in the register, printing -294967296 (two’s-complement wraparound). Notice also the use of PRId32 from <inttypes.h>: on arm-none-eabi-gcc (where int32_t is long int) and on 16-bit MCUs (where int is 16-bit), passing int32_t to %d causes a format mismatch. At -O2, when inputs are runtime unknowns across inlined call sites or when algebraic reasoning kicks in, the compiler assumes raw * factor never overflows in a valid program and simplifies downstream logic accordingly (with compile-time constants in the same translation unit, -O2 may constant-fold and warn with -Woverflow rather than wrapping predictably at runtime).

Why Optimization Changes Behavior

The compiler’s reasoning at -O2 follows a chain of logical deductions that are valid under the C abstract machine but surprising to engineers:

  1. Premise: Signed overflow is undefined behavior (C17 6.5p5 / C23 6.5.1p5).
  2. Assumption: A valid execution never executes undefined behavior.
  3. Inference: Therefore, raw * factor never overflows in any valid execution.
  4. Optimization: Any downstream branch that exists solely to detect overflow is dead code and can be removed.
#include <limits.h>
#include <stdint.h>
/* DANGEROUS: check AFTER signed overflow has already occurred (assuming factor != 0) */
int32_t scale_sensor_checked(int32_t raw, int32_t factor) {
if (factor == 0) {
return 0;
}
int32_t result = raw * factor; // UB happens HERE if product overflows
if (result / factor != raw) { // Eliminated at -O2!
return (raw > 0) == (factor > 0) ? INT32_MAX : INT32_MIN;
}
return result;
}

When factor != 0 and no overflow occurred, (raw * factor) / factor is algebraically equal to raw. Because the optimizer assumes raw * factor never overflows, it simplifies result / factor != raw to raw != raw (false) and eliminates the entire if block — removing the division (SDIV or __aeabi_idiv), comparison, and conditional branch as dead code.

Optimization Removes Post-Operation Overflow Checks at -O2

+-----------------------------------+-----------------------------------+
| SOURCE CODE AT -O0 | OPTIMIZED CODE AT -O2 |
+-----------------------------------+-----------------------------------+
| int32_t result = raw * factor; | int32_t result = raw * factor; |
| -> MUL (low 32 bits wrap) | -> MUL (no overflow check) |
| | |
| if (result / factor != raw) | /* check REMOVED by optimizer */ |
| -> SDIV + CMP + branch | -> No division, no comparison |
| | |
| return saturated or result; | return result; |
| -> Overflow caught by chance | -> Overflow silently propagates |
+-----------------------------------+-----------------------------------+

The generated assembly at -O2 lacks the division and comparison instructions entirely. The overflow check vanishes because the optimizer proves it can never be true under the assumption that the program contains no undefined behavior. This is not a compiler bug; it is legal optimization under the C standard.

The Loop Transformation Hazard

A classic example appears in loop termination conditions:

#include <stdint.h>
void process(int32_t value);
void run_powers_of_two(void) {
for (int32_t i = 1; i > 0; i *= 2) {
process(i);
}
}

At -O0, this loops until i overflows INT32_MAX and wraps to -2147483648 on two’s-complement hardware. At -O2, GCC can transform this into an infinite loop because i starts positive and multiplying a positive signed integer by 2 can never yield a non-positive result without signed overflow. The loop condition i > 0 is therefore proven always true. This optimization was documented in the GCC 4.2 release notes (2007) as a direct consequence of -fstrict-overflow (enabled by default at -O2).

The Solution: Builtin Checked Arithmetic

GCC (since version 5.1, released 2015) and Clang (since version 3.8, released 2016) provide builtin functions that perform checked arithmetic without invoking undefined behavior. These builtins promote both operands to infinite-precision signed arithmetic, compute the exact mathematical result, convert and store the low-order bits (two’s-complement modulo 2^W for a W-bit destination type) into an output pointer, and return a boolean indicating whether the stored value differs from the mathematical result.

Core Builtins

#include <stdbool.h>
#include <stdint.h>
/* Type-generic compiler builtins (conceptual signatures -- do NOT redeclare
* in headers, as GCC/Clang treat them as intrinsic polymorphic builtins):
*
* bool __builtin_add_overflow(type1 a, type2 b, type3 *out);
* bool __builtin_sub_overflow(type1 a, type2 b, type3 *out);
* bool __builtin_mul_overflow(type1 a, type2 b, type3 *out);
*
* Compile-time / side-effect-free predicate forms (GCC 7+, Clang) -- the 3rd
* argument is a dummy value whose type selects the target range; no write occurs:
*
* bool __builtin_add_overflow_p(type1 a, type2 b, type3 target_type_expr);
* bool __builtin_sub_overflow_p(type1 a, type2 b, type3 target_type_expr);
* bool __builtin_mul_overflow_p(type1 a, type2 b, type3 target_type_expr);
*/
/* Explicit signed variants (int, long, long long) */
void explicit_signed_examples(int si, long sl, long long sll,
int *oi, long *ol, long long *oll) {
(void)__builtin_sadd_overflow(si, si, oi);
(void)__builtin_saddl_overflow(sl, sl, ol);
(void)__builtin_saddll_overflow(sll, sll, oll);
/* Corresponding subtraction and multiplication families:
* __builtin_ssub_overflow, __builtin_ssubl_overflow, __builtin_ssubll_overflow
* __builtin_smul_overflow, __builtin_smull_overflow, __builtin_smulll_overflow
*/
}
/* Explicit unsigned variants (unsigned int, unsigned long, unsigned long long) */
void explicit_unsigned_examples(unsigned int ui, unsigned long ul,
unsigned long long ull,
unsigned int *oui, unsigned long *oul,
unsigned long long *oull) {
(void)__builtin_uadd_overflow(ui, ui, oui);
(void)__builtin_uaddl_overflow(ul, ul, oul);
(void)__builtin_uaddll_overflow(ull, ull, oull);
/* Corresponding subtraction and multiplication families:
* __builtin_usub_overflow, __builtin_usubl_overflow, __builtin_usubll_overflow
* __builtin_umul_overflow, __builtin_umull_overflow, __builtin_umulll_overflow
*/
}

Prefer the type-generic __builtin_add_overflow, __builtin_sub_overflow, and __builtin_mul_overflow forms in embedded code. Unlike __builtin_uadd_overflow (which strictly expects unsigned int * — a mismatch with uint32_t * on 16-bit MCUs where uint32_t is unsigned long), the type-generic builtins work uniformly across int8_t through int64_t, uint8_t through uint64_t, and size_t, and even allow mixed operand and destination types (for example, uint32_t + int32_t stored into int32_t *). In GCC, the output pointer *out may point to any integral type other than bool or an enumerated type (Clang’s type-generic builtins also permit bool).

Safe Sensor Scaling Example

#include <limits.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
/* SAFE: detects overflow without UB at any optimization level */
bool scale_sensor_safe(int32_t raw, int32_t factor, int32_t *out) {
if (out == NULL) {
return false;
}
return !__builtin_mul_overflow(raw, factor, out);
}
/* Alternative: saturate to INT32_MAX / INT32_MIN on overflow */
int32_t scale_sensor_saturate(int32_t raw, int32_t factor) {
int32_t result = 0;
if (__builtin_mul_overflow(raw, factor, &result)) {
return (raw > 0) == (factor > 0) ? INT32_MAX : INT32_MIN;
}
return result;
}

The __builtin_mul_overflow call never invokes signed-overflow undefined behavior. It evaluates the exact mathematical product in infinite signed precision, checks whether that product fits in int32_t, stores the low 32 bits (two’s-complement wraparound) into result, and returns true if overflow occurred. Notice in scale_sensor_saturate that (raw > 0) == (factor > 0) handles all four non-zero sign combinations: if both raw and factor are negative (for example, INT32_MIN * -1), their product is positive and saturates to INT32_MAX.

Builtin Checked Arithmetic Flow

+--------------------------------------------------------------------------+
| __builtin_mul_overflow(a, b, &result) |
+--------------------------------------------------------------------------+
| |
| 1. Promote operands and compute exact infinite-precision signed math: |
| true_product = a * b |
| |
| +--------------------------------------+ |
| | Does true_product fit in *result? | |
| +--------------------------------------+ |
| | | |
| YES NO |
| | | |
| v v |
| +--------------------------+ +--------------------------+ |
| | Store true_product into | | Store low W bits | |
| | *result | | (wrapped modulo 2^W) | |
| | | | into *result | |
| | Return false | | Return true | |
| | (no overflow) | | (overflow detected) | |
| +--------------------------+ +--------------------------+ |
| |
| *result always holds a defined bit pattern (given valid non-null ptr). |
+--------------------------------------------------------------------------+

Handling INT_MIN * -1, INT_MIN / -1, and INT_MIN % -1

Negating or multiplying INT32_MIN (-2147483648) by -1 yields +2147483648, which equals INT32_MAX + 1 — one greater than the maximum representable int32_t. The checked multiplication builtin handles INT32_MIN * -1 cleanly without UB:

#include <stdbool.h>
#include <stdint.h>
void check_negate_min(void) {
int32_t a = INT32_MIN; // -2147483648
int32_t b = -1;
int32_t result = 0;
bool overflow = __builtin_mul_overflow(a, b, &result);
(void)overflow;
/* overflow == true, result == INT32_MIN (wrapped modulo 2^32) */
}

For division and remainder, INT32_MIN / -1 and INT32_MIN % -1 are a distinct hazard. Under C17 Section 6.5.5p6 (and C23 Section 6.5.6p6), if the quotient a / b is not representable in the result type, both a / b and a % b invoke undefined behavior — even though the mathematical remainder of INT32_MIN % -1 is 0. On x86/x86_64, the IDIV instruction computes quotient and remainder together and raises a #DE hardware exception (SIGFPE on POSIX). On ARM Cortex-M, the SDIV instruction returns INT32_MIN without trapping, yet the C compiler can still treat a == INT32_MIN && b == -1 as unreachable under UB assumptions.

Division and Remainder Overflow

Because GCC/Clang checked builtins only cover addition, subtraction, and multiplication, division and remainder overflow (b == 0 and INT_MIN / -1) must be guarded manually before executing / or %:

#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
bool safe_div(int32_t a, int32_t b, int32_t *out) {
if (out == NULL || b == 0) {
return false;
}
if (a == INT32_MIN && b == -1) {
return false; // Quotient INT32_MAX + 1 is not representable
}
*out = a / b;
return true;
}
bool safe_mod(int32_t a, int32_t b, int32_t *out) {
if (out == NULL || b == 0) {
return false;
}
if (a == INT32_MIN && b == -1) {
return false; // C standard marks both a / b and a % b UB here
}
*out = a % b;
return true;
}

C23 Standardization: <stdckdint.h>

C23 (ISO/IEC 9899:2024, Clause 7.20) introduces <stdckdint.h>, defining the feature-test macro __STDC_VERSION_STDCKDINT_H__ (202311L) and three type-generic macros in Section 7.20.1:

#include <stdckdint.h>
#include <stdbool.h>
#include <stdint.h>
void c23_example(int32_t a, int32_t b) {
int32_t sum = 0;
int32_t diff = 0;
int32_t prod = 0;
/* ckd_add(result_ptr, a, b) -> bool
* Note: result_ptr is FIRST (opposite to __builtin_*_overflow).
* Returns true on overflow, false when the mathematical result fits. */
bool add_ovf = ckd_add(&sum, a, b);
bool sub_ovf = ckd_sub(&diff, a, b);
bool mul_ovf = ckd_mul(&prod, a, b);
(void)add_ovf;
(void)sub_ovf;
(void)mul_ovf;
}

Watch out for two critical details when migrating to <stdckdint.h>:

  1. Reversed argument order: C23’s ckd_add(&result, a, b) places the destination pointer first, whereas GCC/Clang’s __builtin_add_overflow(a, b, &result) places it last.
  2. Type restrictions: Per C23 Section 7.20.1, both operands and *result may be any standard or extended signed/unsigned integer type except plain char, bool, bit-precise integer types (_BitInt(N)), or enumerated types. Use signed char or uint8_t instead of plain char.

In GCC and Clang, <stdckdint.h> expands directly to __builtin_add_overflow, __builtin_sub_overflow, and __builtin_mul_overflow. Native <stdckdint.h> support landed in GCC 14 (-std=c23 or -std=gnu23) and Clang 18 (which also exposes <stdckdint.h> in pre-C23 modes as an extension).

Portable Wrapper for Pre-C23 and Mixed Toolchains

For projects not yet on C23, a small compatibility header can map CK_ADD, CK_SUB, and CK_MUL to C23 <stdckdint.h> when available, fall back to compiler builtins on GCC/Clang/IAR, and provide UB-free typed static inline helpers on toolchains without builtins. Avoid naive fallback macros that compute (a) + (b) before checking (that still triggers signed overflow UB!) or evaluate arguments multiple times:

/* checked_arithmetic.h - portable UB-free checked arithmetic wrapper */
#ifndef CHECKED_ARITHMETIC_H
#define CHECKED_ARITHMETIC_H
#include <limits.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <string.h>
#if defined(__has_builtin)
# define CK_HAS_BUILTIN(x) __has_builtin(x)
#else
# define CK_HAS_BUILTIN(x) 0
#endif
#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 202311L
# ifdef __has_include
# if __has_include(<stdckdint.h>)
# include <stdckdint.h>
# define CK_USE_STDCKDINT 1
# endif
# endif
#endif
#if defined(CK_USE_STDCKDINT)
# define CK_ADD(res, a, b) ckd_add((res), (a), (b))
# define CK_SUB(res, a, b) ckd_sub((res), (a), (b))
# define CK_MUL(res, a, b) ckd_mul((res), (a), (b))
#elif (defined(__GNUC__) && __GNUC__ >= 5 && !defined(__ICC) && !defined(__clang__)) || \
(CK_HAS_BUILTIN(__builtin_add_overflow) && \
CK_HAS_BUILTIN(__builtin_sub_overflow) && \
CK_HAS_BUILTIN(__builtin_mul_overflow))
# define CK_ADD(res, a, b) __builtin_add_overflow((a), (b), (res))
# define CK_SUB(res, a, b) __builtin_sub_overflow((a), (b), (res))
# define CK_MUL(res, a, b) __builtin_mul_overflow((a), (b), (res))
#else
/* UB-free inline fallbacks for compilers without builtins (e.g. legacy C99/MSVC).
* Unsigned arithmetic wraps modulo 2^W cleanly, and memcpy copies the two's-
* complement bit pattern without signed-overflow UB or strict-aliasing issues. */
static inline bool ck_add_i32_fallback(int32_t *res, int32_t a, int32_t b) {
uint32_t ua = (uint32_t)a;
uint32_t ub = (uint32_t)b;
uint32_t sum = ua + ub;
memcpy(res, &sum, sizeof(sum));
return (((ua ^ sum) & (ub ^ sum)) >> 31) != 0U;
}
static inline bool ck_sub_i32_fallback(int32_t *res, int32_t a, int32_t b) {
uint32_t ua = (uint32_t)a;
uint32_t ub = (uint32_t)b;
uint32_t diff = ua - ub;
memcpy(res, &diff, sizeof(diff));
return (((ua ^ ub) & (ua ^ diff)) >> 31) != 0U;
}
static inline bool ck_mul_i32_fallback(int32_t *res, int32_t a, int32_t b) {
int64_t prod = (int64_t)a * (int64_t)b;
uint32_t low = (uint32_t)(uint64_t)prod;
memcpy(res, &low, sizeof(low));
return (prod > INT32_MAX) || (prod < INT32_MIN);
}
static inline bool ck_add_u32_fallback(uint32_t *res, uint32_t a, uint32_t b) {
uint32_t sum = a + b;
*res = sum;
return sum < a;
}
static inline bool ck_sub_u32_fallback(uint32_t *res, uint32_t a, uint32_t b) {
*res = a - b;
return a < b;
}
static inline bool ck_mul_u32_fallback(uint32_t *res, uint32_t a, uint32_t b) {
*res = a * b;
return (a != 0U) && (b > (UINT32_MAX / a));
}
static inline bool ck_add_u16_fallback(uint16_t *res, uint16_t a, uint16_t b) {
uint32_t sum = (uint32_t)a + (uint32_t)b;
*res = (uint16_t)sum;
return sum > UINT16_MAX;
}
static inline bool ck_mul_size_fallback(size_t *res, size_t a, size_t b) {
*res = a * b; /* Unsigned multiplication is defined modulo SIZE_MAX + 1 */
return (a != 0U) && (b > (SIZE_MAX / a));
}
# if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
/* Dispatch on the target pointer in C11/C17; note uint32_t vs size_t can alias on
* ILP32 targets, so select distinct fixed-width or size helpers explicitly when needed. */
# define CK_ADD(res, a, b) _Generic((res), \
int32_t *: ck_add_i32_fallback, \
uint32_t *: ck_add_u32_fallback, \
uint16_t *: ck_add_u16_fallback)(res, a, b)
# define CK_SUB(res, a, b) _Generic((res), \
int32_t *: ck_sub_i32_fallback, \
uint32_t *: ck_sub_u32_fallback)(res, a, b)
# define CK_MUL(res, a, b) _Generic((res), \
int32_t *: ck_mul_i32_fallback, \
uint32_t *: ck_mul_u32_fallback)(res, a, b)
# else
/* Pre-C11 / C++ without builtins: call typed helpers (e.g., ck_add_i32_fallback)
* directly, or add C++ overloaded inline wrappers. */
# endif
#endif
#endif /* CHECKED_ARITHMETIC_H */

Notice two important defensive practices in that header:

  • Always guard defined(__STDC_VERSION__) and #ifdef __has_include on separate preprocessor lines so older compilers without __has_include do not fail preprocessing, and C++ translation units do not emit -Wundef on __STDC_VERSION__.
  • Never place both uint32_t * and size_t * inside the same C11 _Generic association list: on 32-bit targets like Cortex-M (ILP32), size_t and uint32_t can map to the same underlying unsigned int or unsigned long type, causing a duplicate-type compile error. Keep ck_mul_size_fallback (or __builtin_mul_overflow / ckd_mul) explicit for size_t when supporting non-builtin fallback toolchains.

C23 Migration Path

Using CK_ADD(&result, a, b), CK_SUB(&result, a, b), and CK_MUL(&result, a, b) from checked_arithmetic.h lets your codebase compile cleanly on pre-C23 GCC/Clang toolchains today and automatically switch to standard <stdckdint.h> once your build moves to -std=c23. Keep the (&result, a, b) argument order identical to C23 <stdckdint.h> from day one so the eventual migration is a trivial header cleanup.

Real-World Patterns: Sensor Processing, PID, Checksums

Embedded firmware frequently performs arithmetic on sensor data, control loop calculations, buffer allocations, and protocol checksums — all of which can overflow under fault inputs or edge conditions.

Sensor Data Accumulation

#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include "checked_arithmetic.h"
/* Accumulate N samples with overflow detection */
bool accumulate_samples(const int16_t *samples, size_t count, int32_t *out) {
if (samples == NULL || out == NULL) {
return false;
}
int32_t sum = 0;
for (size_t i = 0; i < count; ++i) {
if (CK_ADD(&sum, sum, (int32_t)samples[i])) {
return false; // Overflow detected
}
}
*out = sum;
return true;
}

PID Controller Output Clamping

When saturating an overflowing signed multiplication in a PID loop, you must check the signs of both factors. Testing only (error > 0) fails if a reverse-acting controller uses negative gains (error < 0 and kp < 0 yields a positive product that must saturate to INT32_MAX, not INT32_MIN). Extracting small helpers avoids duplicating saturation logic across all terms:

#include <limits.h>
#include <stdint.h>
#include "checked_arithmetic.h"
static inline int32_t sat_mul_i32(int32_t a, int32_t b) {
int32_t res = 0;
if (CK_MUL(&res, a, b)) {
return ((a > 0) == (b > 0)) ? INT32_MAX : INT32_MIN;
}
return res;
}
static inline int32_t sat_add_i32(int32_t a, int32_t b) {
int32_t res = 0;
if (CK_ADD(&res, a, b)) {
/* Overflow in addition only occurs when a and b share the same sign */
return (a > 0) ? INT32_MAX : INT32_MIN;
}
return res;
}
/* PID output with UB-free saturation arithmetic */
int16_t pid_compute(int32_t error, int32_t kp, int32_t ki, int32_t kd,
int32_t integral, int32_t derivative) {
int32_t p_term = sat_mul_i32(error, kp);
int32_t i_term = sat_mul_i32(integral, ki);
int32_t d_term = sat_mul_i32(derivative, kd);
int32_t output = sat_add_i32(sat_add_i32(p_term, i_term), d_term);
/* Clamp to int16_t range for actuator */
if (output > INT16_MAX) return INT16_MAX;
if (output < INT16_MIN) return INT16_MIN;
return (int16_t)output;
}

Protocol Checksum (One’s-Complement Carry Detection)

#include <stddef.h>
#include <stdint.h>
#include "checked_arithmetic.h"
/* 16-bit one's-complement checksum (RFC 1071 style) using explicit carry detection */
uint16_t compute_checksum(const uint8_t *data, size_t len) {
uint16_t sum = 0;
size_t i = 0;
while (i + 1U < len) {
uint16_t word = (uint16_t)(((uint16_t)data[i] << 8) | data[i + 1U]);
if (CK_ADD(&sum, sum, word)) {
/* End-around carry: 0xFFFF + 0xFFFF wraps to 0xFFFE, so +1 never re-overflows */
sum = (uint16_t)(sum + 1U);
}
i += 2U;
}
if (i < len) {
uint16_t tail = (uint16_t)((uint16_t)data[i] << 8);
if (CK_ADD(&sum, sum, tail)) {
sum = (uint16_t)(sum + 1U);
}
}
return (uint16_t)(~sum);
}

Note: Unsigned overflow in C is defined to wrap modulo 2^N (C17 Section 6.2.5p9 / C23 Section 6.2.5p11). Checked arithmetic on unsigned types (CK_ADD / __builtin_add_overflow) does not prevent UB — there is no unsigned overflow UB — rather, it gives you a portable, flag-based carry bit for one’s-complement checksums, multi-precision math, or allocation bounds checks.

Memory Size Calculations

A classic vulnerability (CWE-190 leading to CWE-122) is computing an allocation size in size_t that wraps around to a tiny byte count:

#include <stdbool.h>
#include <stddef.h>
#include <stdlib.h>
#include "checked_arithmetic.h"
/* DANGEROUS: size_t multiplication wraps modulo SIZE_MAX + 1 (not UB),
* producing an undersized allocation and subsequent heap buffer overflow! */
void *alloc_array(size_t count, size_t element_size) {
return malloc(count * element_size);
}
/* SAFE: checked multiplication before allocation */
bool alloc_array_safe(size_t count, size_t element_size, void **out) {
if (out == NULL) {
return false;
}
size_t total = 0;
if (CK_MUL(&total, count, element_size) || total == 0U) {
*out = NULL;
return false;
}
*out = malloc(total);
return *out != NULL;
}

Note that CK_MUL on size_t works seamlessly with C23 ckd_mul and __builtin_mul_overflow; if targeting legacy compilers without builtins, call ck_mul_size_fallback directly instead of the uint32_t * _Generic dispatch. Rejecting total == 0U also avoids implementation-defined malloc(0) behavior.

Timestamp Arithmetic

In embedded firmware, monotonic tick counters (such as STM32 HAL_GetTick(), FreeRTOS xTaskGetTickCount(), or Zephyr k_uptime_get_32()) should use unsigned types like uint32_t, where (uint32_t)(end - start) handles wraparound (~49.7 days at 1 kHz) cleanly with well-defined modular arithmetic.

When interfacing with legacy APIs that store timestamps or deltas in signed int32_t (which reaches INT32_MAX after ~24.85 days at 1 kHz), raw end - start invokes UB whenever the mathematical difference lies outside [INT32_MIN, INT32_MAX]:

#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include "checked_arithmetic.h"
int32_t legacy_ms_since_boot(void);
/* DANGEROUS: UB if mathematical difference is < INT32_MIN or > INT32_MAX */
int32_t elapsed_ms(int32_t start, int32_t end) {
return end - start;
}
/* SAFE: detects if difference cannot be represented in int32_t */
bool elapsed_ms_safe(int32_t start, int32_t end, int32_t *out) {
if (out == NULL) {
return false;
}
return !CK_SUB(out, end, start);
}

Compiler Support and Feature Detection

CompilerVersionOverflow Builtins (__builtin_*_overflow)<stdckdint.h>
GCC5.1+Yes (__builtin_*_overflow_p in 7+)14.1+ (-std=c23 / -std=gnu23)
Clang3.8+Yes18.1+ (exposed in pre-C23 modes too)
Arm Compiler (armclang)6.xYes (LLVM/Clang-based)Depends on bundled Clang/libc version
IAR (EWARM)8.50+ / 9.xPartial (requires matching operand/output types & GNU extensions)No (check vendor release notes)
MSVC (cl.exe)VS 2022 17.7+No (uses <intrin.h> _add_overflow_i32, etc.; clang-cl supports GCC builtins)No

Feature Test Macros

Note that Clang defines __GNUC__ as 4 for historical compatibility, so checking defined(__GNUC__) && __GNUC__ >= 5 alone misses Clang. Always pair __has_builtin with the GCC version check, and guard defined(__STDC_VERSION__) and #ifdef __has_include on separate lines:

#if defined(__has_builtin)
# define CK_HAS_ADD_OVERFLOW __has_builtin(__builtin_add_overflow)
# define CK_HAS_MUL_OVERFLOW __has_builtin(__builtin_mul_overflow)
#else
# define CK_HAS_ADD_OVERFLOW 0
# define CK_HAS_MUL_OVERFLOW 0
#endif
#if (defined(__GNUC__) && __GNUC__ >= 5 && !defined(__clang__) && !defined(__ICC)) || \
(CK_HAS_ADD_OVERFLOW && CK_HAS_MUL_OVERFLOW)
# define CK_HAS_BUILTINS 1
#else
# define CK_HAS_BUILTINS 0
#endif
#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 202311L
# ifdef __has_include
# if __has_include(<stdckdint.h>)
# define CK_HAS_STDCKDINT 1
# else
# define CK_HAS_STDCKDINT 0
# endif
# else
# define CK_HAS_STDCKDINT 0
# endif
#else
# define CK_HAS_STDCKDINT 0
#endif

IAR Embedded Workbench (with GNU language extensions enabled, e.g., --language=gnu) supports GCC overflow builtins with stricter typing: operands must match the type pointed to by the output argument or be constants convertible without loss. MSVC cl.exe does not implement __builtin_*_overflow; on Visual Studio 2022 17.7+, <intrin.h> provides MSVC-specific intrinsics such as _add_overflow_i32, _sub_overflow_i32, and _mul_overflow_i32 (older MSVC versions use _addcarry_u32/_addcarry_u64 for unsigned carry, <intsafe.h>, or int64_t widening).

Performance Characteristics

On architectures with 64-bit widening multiply instructions — including both ARM Cortex-M3 (ARMv7-M) and Cortex-M4/M7 (ARMv7E-M) — 32-bit __builtin_mul_overflow compiles to SMULL (which executes in 1 cycle on Cortex-M4, or 3-7 cycles with early termination on Cortex-M3) followed by an arithmetic shift (ASR), compare (CMP), and branch/conditional move, with no division instruction:

#include <limits.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
/* Manual pre-check for signed multiply: requires NULL/0 handling + 4 sign cases + SDIV */
bool manual_mul_i32(int32_t a, int32_t b, int32_t *out) {
if (out == NULL) {
return false;
}
if (a > 0) {
if (b > 0) {
if (a > INT32_MAX / b) return false;
} else if (b < 0) {
if (b < INT32_MIN / a) return false;
}
} else if (a < 0) {
if (b > 0) {
if (a < INT32_MIN / b) return false;
} else if (b < 0) {
if (b < INT32_MAX / a) return false;
}
}
*out = a * b;
return true;
}
/* Builtin: SMULL + ASR + CMP + conditional store/return (no division, no 4-way branch) */
bool builtin_mul_i32(int32_t a, int32_t b, int32_t *out) {
if (out == NULL) {
return false;
}
return !__builtin_mul_overflow(a, b, out);
}

On ARM Cortex-M0/M0+ (ARMv6-M), hardware includes a 32x32->32 MULS instruction (1 or 32 cycles depending on silicon option) but no 64-bit SMULL or hardware SDIV. Consequently, 32-bit __builtin_mul_overflow invokes a compiler helper (__aeabi_lmul / __muldi3 in libgcc or compiler-rt), whereas __builtin_add_overflow and __builtin_sub_overflow still lower directly to single ADDS / SUBS flag checks (BVS / BCS) even on Cortex-M0. On RISC-V with the M extension (RV32IM), the compiler emits MUL (low 32 bits) and MULH (high 32 bits) followed by a sign-extension check, avoiding any library call.

Verification: Testing With UBSan

Always verify arithmetic-heavy code using Undefined Behavior Sanitizer (UBSan) across both hosted unit tests and target builds. Note a critical toolchain distinction:

  1. Hosted / Linux user-space testing (libubsan diagnostic output): Host GCC/Clang and arm-linux-gnueabihf-gcc ship the libubsan runtime, which prints detailed file/line diagnostics to stderr and can run natively on x86_64 or under qemu-arm user-mode emulation.
  2. Bare-metal Cortex-M testing (trap-mode UBSan): Bare-metal arm-none-eabi-gcc typically does not ship libubsan (no OS stderr or POSIX runtime). Passing -fsanitize=undefined alone fails at link time with missing __ubsan_handle_* symbols. Add -fsanitize-trap=undefined on GCC 13+ or Clang (on GCC 12 and earlier, use -fsanitize-undefined-trap-on-error, deprecated in GCC 13+; in C++, disable -fsanitize=vptr with -fno-sanitize=vptr since vptr requires runtime support) so violations execute an inline UDF trap instruction that enters UsageFault / HardFault under your debugger or qemu-system-arm system emulation.
# 1. Hosted test build with full libubsan diagnostic messages
gcc -fsanitize=undefined -fno-sanitize-recover=all -O2 -g \
checked_arithmetic.c -o checked_arithmetic_host.elf
./checked_arithmetic_host.elf
# 2. Bare-metal Cortex-M4 build using trap-mode UBSan (GCC 13+; no libubsan needed)
arm-none-eabi-gcc -mcpu=cortex-m4 -mthumb -O2 -g \
-fsanitize=undefined -fsanitize-trap=undefined \
-c checked_arithmetic.c -o checked_arithmetic.o

On the hosted build (on a target where int32_t maps to int), any missed signed overflow prints an immediate diagnostic and aborts:

checked_arithmetic.c:38:16: runtime error: signed integer overflow: 2000000000 * 2 cannot be represented in type 'int'

CI Integration

Configure CI to verify host logic with libubsan and compile target Cortex-M code with trap-mode UBSan (note -std=c23 requires GCC 14+ or Clang 18+; on Ubuntu runners with GCC 13, use -std=c2x or install gcc-14 / clang-18):

# .github/workflows/test.yml
jobs:
test-host:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install GCC 14 (for C23 stdckdint.h)
run: sudo apt-get update && sudo apt-get install -y gcc-14
- name: Build and run host tests with UBSan
run: |
gcc-14 -fsanitize=undefined -fno-sanitize-recover=all -O2 -g -std=c23 \
-Wall -Wextra -Werror \
src/*.c tests/*.c -o test_host.elf
./test_host.elf
build-target-ubsan:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install Arm GNU Toolchain
run: sudo apt-get update && sudo apt-get install -y gcc-arm-none-eabi
- name: Compile Cortex-M4 firmware with trap-mode UBSan
run: |
arm-none-eabi-gcc -mcpu=cortex-m4 -mthumb -mfloat-abi=hard -mfpu=fpv4-sp-d16 \
-O2 -g -fsanitize=undefined -fsanitize-trap=undefined \
-Wall -Wextra -Werror \
-c src/*.c

Migration Checklist

When adopting checked arithmetic in an existing codebase:

  1. Audit all signed arithmetic in critical paths: sensor scaling, control loops, protocol parsing, memory size calculations, and legacy signed timestamp differences.
  2. Replace unchecked operations with CK_ADD, CK_SUB, CK_MUL (keeping C23 (&result, a, b) argument order).
  3. Decide overflow policy per call site: saturate, return an error, trap/assert, or document intentional unsigned wraparound.
  4. Enable -fsanitize=undefined (-fno-sanitize-recover=all on host; trap mode on bare-metal targets) in CI.
  5. Test at -O2 and -O3 — the optimization levels where UB-driven check elimination manifests.
  6. Document the pattern in your coding standard and check third-party HALs/middleware for unchecked scaling or buffer-size math.
  7. Add regression tests for boundary inputs (INT32_MAX * 2, INT32_MIN * -1, INT32_MIN / -1, INT32_MIN % -1, negative-times-negative saturation, and SIZE_MAX allocation multiplication).

Summary

Signed integer overflow is undefined behavior in C. Optimizing compilers assume it never happens and aggressively eliminate post-operation overflow checks or loop bounds at -O2 and -O3. Checked arithmetic builtins (__builtin_add_overflow, __builtin_sub_overflow, __builtin_mul_overflow) and C23 <stdckdint.h> (ckd_add, ckd_sub, ckd_mul) eliminate this class of bugs by evaluating operands in infinite-precision signed math, storing the low-order wrapped bits, and returning a defined overflow flag at every optimization level. Pair these primitives with explicit safe_div / safe_mod guards for INT_MIN / -1, UB-free pre-C23 fallbacks, and UBSan verification in CI.

References

  1. ISO/IEC 9899:2018 (C17 draft N2176), Section 6.5 paragraph 5 & Section 6.2.5 paragraph 9 — WG14 N2176 PDF
  2. ISO/IEC 9899:2024 (C23 draft N3220), Section 6.5.1 paragraph 5 & Section 7.20 <stdckdint.h> — WG14 N3220 PDF
  3. GCC Manual, “Integer Overflow Builtins” — https://gcc.gnu.org/onlinedocs/gcc/Integer-Overflow-Builtins.html
  4. GCC 14 Release Series Changes (<stdckdint.h> and -std=c23) — https://gcc.gnu.org/gcc-14/changes.html
  5. Clang Language Extensions, “Checked Arithmetic Builtins” — https://clang.llvm.org/docs/LanguageExtensions.html#checked-arithmetic-builtins
  6. Clang 18.1.0 Release Notes (<stdckdint.h>) — https://releases.llvm.org/18.1.0/tools/clang/docs/ReleaseNotes.html
  7. GCC Instrumentation Options (-fsanitize=undefined) — https://gcc.gnu.org/onlinedocs/gcc/Instrumentation-Options.html
  8. Clang UndefinedBehaviorSanitizer Documentation — https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html
  9. Memfault Interrupt Blog, “Undefined Behavior Sanitizer Trap on Error” — https://interrupt.memfault.com/blog/ubsan-trap
  10. Will Dietz, Peng Li, John Regehr, and Vikram Adve, “Understanding Integer Overflow in C/C++” (ICSE 2012) — https://www.cs.utah.edu/~regehr/papers/overflow12.pdf

Frequently Asked Questions

What is signed integer overflow in C?

Signed integer overflow occurs when a signed arithmetic operation produces a mathematical result outside the representable range of the promoted signed type. In C, this is undefined behavior -- the compiler may assume it never happens and optimize accordingly.

Why does signed overflow break at -O2 but work at -O0?

At -O0, compilers typically emit straightforward fixed-width two's-complement machine instructions without cross-statement algebraic assumptions. At -O2, the optimizer exploits the undefined behavior rule -- it may eliminate post-operation overflow checks, fold comparisons, or turn loops into infinite loops under the assumption that signed overflow never occurs in a valid program.

How do __builtin_add_overflow and related builtins work?

These GCC and Clang builtins promote both operands to infinite-precision signed arithmetic, compute the exact mathematical result, convert and store the wrapped value in the output pointer, and return a boolean indicating whether the stored value differs from the mathematical result. With a valid writable output pointer, they have fully defined behavior at any optimization level.

What is the C23 stdckdint.h header?

C23 (ISO/IEC 9899:2024, Section 7.20) standardizes checked arithmetic via <stdckdint.h> with type-generic macros ckd_add, ckd_sub, and ckd_mul (supported in GCC 14+ and Clang 18+). Unlike the GCC/Clang builtins, these macros take the result pointer as the first argument (ckd_add(&result, a, b)) and return true if overflow occurred.

Can I use checked arithmetic in C++?

Yes. GCC and Clang expose __builtin_add_overflow, __builtin_sub_overflow, and __builtin_mul_overflow directly in C++ mode. Clang 18+ also exposes <stdckdint.h> in C++ mode as an extension, newer libstdc++ provides C++ compatibility, and C++26 adds standard <stdckdint.h> compatibility alongside saturating helpers such as std::add_sat and std::mul_sat in <numeric>.

Tags

embedded-cinteger-overflowundefined-behaviorgccclangc23

Share


Previous Article
Fixing Yocto Bitbake Out-of-Memory Build Failures
Jithin Tom

Jithin Tom

A Closer Look at C/C++, RTOS, and Embedded Systems

Related Posts

Fixing Function Pointer Corruption from Buffer Overruns in C
Fixing Function Pointer Corruption from Buffer Overruns in C
November 27, 2026
8 min
© 2026, All Rights Reserved.
Powered By Netlyft

Quick Links

Advertise with usAbout UsContact Us

Social Media