Contents

Integer overflow

Detects overflow in arithmetic.

Overview

Overflows result in undefined behavior. Use this check to detect overflows in addition, subtraction, multiplication, and division. Available in Xcode 9 and later.

Signed addition overflow in C

In the following code, the x variable has the maximum int32_t value before the addition, and the result of the addition overflows x, which the optimizer may not handle in a predictable way:

int32_t x = (1U << 31) - 1;
x += 1; // Error: the add result can't fit in x

Solution

One way to address signed overflow is to use larger types.

If you don’t need to represent negative numbers, another option is to use unsigned types, which wrap on arithmetic overflow. Alternatively, pass the -fwrapv flag to the compiler to enable signed wraparound on overflow. However, this may adversely impact performance.

See Also

Undefined Behavior Sanitizer