Taskcore
Detect integer overflow
Also called checked addition, overflow check, checked_add, Math.addExact, __builtin_add_overflow, ckd_add, checked context, safe integer arithmetic.
Add two 64-bit integers and report an overflow instead of a wrong sum. Use a checked operation, a compiler builtin or a test of the operands before the addition.
- Evidence
- Code in 10 languages
Task
Add two 64-bit signed integers. Return the sum when it fits in 64 bits. When it does not fit, report the overflow, and do not return a wrong sum.
The function checked_add(a, b) returns a + b, or no value. For example, checked_add(2, 3) is 5, and checked_add(9223372036854775807, 1) has no value, because 9223372036854775807 is the largest 64-bit signed integer.
The plain + operator does not do this check in most languages. In C, "When signed integer arithmetic operation overflows (the result does not fit in the result type), the behavior is undefined"1. In Go, the sum wraps around, and "Overflow does not cause a run-time panic"2. In Java, "The integer operators do not indicate overflow or underflow in any way"3, and the sum wraps. In C#, the sum also wraps by default4. See Integer overflow behaviour for the rule of each language.
There are three ways to detect the overflow:
- A checked operation. A library function or a language feature does the addition and reports the overflow:
Math.addExactin Java,checked_addin Rust, acheckedcontext in C#. - A compiler builtin. GCC and Clang have
__builtin_add_overflow, and C23 hasckd_add. They compute the exact sum and tell whether it fits. - A test before the operation. Compare the operands with the limits of the type, and add only when the sum fits. With
b > 0, the sum overflows whena > MAX - b. Withb < 0, it overflows whena < MIN - b. These two subtractions cannot overflow. This test works in each language, and in C it is the only way with no undefined behavior and no extension.
Solutions
| Language | Check | The plain operator |
|---|---|---|
| Python | compare the exact sum with the range | exact; Python integers have no fixed width |
| JavaScript, TypeScript | BigInt.asIntN(64, s) === s on BigInt values |
a number is exact only up to 2 ** 53 - 1 |
| Java | Math.addExact, which throws ArithmeticException |
wraps |
| C | __builtin_add_overflow, or a test before the operation |
undefined behavior |
| C++ | a test before the operation | undefined behavior |
| C# | checked(a + b), which throws OverflowException |
wraps in the default unchecked context |
| Go | a sign test after the addition | wraps |
| Rust | i64::checked_add, which returns None |
panics in a debug build |
| Bash | a test before the operation | wraps |
- Python. "Integers have unlimited precision."5 So
a + bis the exact sum, and the solution compares it with the range of a 64-bit integer after the addition. - JavaScript. A
numberis a 64-bit float, so it holds integers exactly only in the safe range from -(2 ** 53 - 1) to 2 ** 53 - 16. The solution usesBigIntvalues, which are exact.BigInt.asIntN"truncates a BigInt value to the given number of bits, and interprets the result as a signed integer"7, soBigInt.asIntN(64, s)is equal tosonly whensfits in 64 bits. - TypeScript. The same code as JavaScript, with the type
bigint. - Java.
Math.addExact(long, long)"Returns the sum of its arguments, throwing an exception if the result overflows a long"8. The solution catches theArithmeticExceptionand returns an emptyOptionalLong. The test file also checks a second form with a test before the operation. - C.
__builtin_add_overflowis a GCC and Clang extension. The GCC manual says that "these built-in functions have fully defined behavior for all argument values"9. The function returns true on overflow. C23 has the same check in<stdckdint.h>:ckd_addreturns "false if the value assigned to *result correctly represents the mathematical result of the addition, true otherwise"10. GCC 13 has no<stdckdint.h>, so the solution uses the builtin, with a portable test before the operation as the second function. - C++. The solution tests the operands with
std::numeric_limits<std::int64_t>before the addition. The function isconstexpr, so astatic_assertcan check it at compile time. - C#. "In a checked context, a System.OverflowException is thrown."4 The solution catches the exception and returns
nullas along?. "The default statement is unchecked"4, and there "addition wraps from the maximum value to the minimum value"4. - Go. The sum wraps, and the wrap is defined behavior. So the solution adds first and tests after: the sum overflowed when
aandbhave the same sign and the sum has the other sign. - Rust.
checked_add"Computes self + rhs" and returnsNone"if overflow occurred"11. A plaina + bis not a check: "Integer operators will panic when they overflow when compiled in debug mode"12, and a build without overflow checks does not report the overflow (see Integer overflow behaviour).checked_addgives the same result in each build. - Bash. "Evaluation is done in the largest fixed-width integers available, with no check for overflow"13. The solution tests the operands before the addition and returns status 1 on overflow.
The Python function:
INT64_MIN, INT64_MAX = -(2**63), 2**63 - 1
def checked_add(a, b):
s = a + b
return s if INT64_MIN <= s <= INT64_MAX else None
print(checked_add(2, 3))
print(checked_add(INT64_MAX, 1))
print(checked_add(INT64_MIN, INT64_MAX))
5
None
-1
The GCC builtin stores the sum wrapped to 64 bits in all cases, and its return value tells whether that stored value is the exact sum:
#include <inttypes.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
int main(void) {
int64_t s;
bool over = __builtin_add_overflow(INT64_MAX, 1, &s);
printf("overflow: %s, stored: %" PRId64 "\n", over ? "yes" : "no", s);
over = __builtin_add_overflow(INT64_MAX - 1, 1, &s);
printf("overflow: %s, stored: %" PRId64 "\n", over ? "yes" : "no", s);
}
overflow: yes, stored: -9223372036854775808
overflow: no, stored: 9223372036854775807
Rust has four forms of the addition. wrapping_add computes the sum "wrapping around at the boundary of the type"11. overflowing_add returns "a tuple of the addition along with a boolean indicating whether an arithmetic overflow would occur"11. saturating_add stops at the limit of the type "instead of overflowing"11:
fn main() {
let a = i64::MAX;
println!("{:?}", a.checked_add(1));
println!("{:?}", a.checked_add(-1));
println!("{}", a.wrapping_add(1));
println!("{:?}", a.overflowing_add(1));
println!("{}", a.saturating_add(1));
}
None
Some(9223372036854775806)
-9223372036854775808
(-9223372036854775808, true)
9223372036854775807
In Go, a test after the addition is correct, because the wrap is defined:
package main
import (
"fmt"
"math"
)
func main() {
var a, b int64 = math.MaxInt64, 1
s := a + b
fmt.Println(s)
fmt.Println("overflow:", (a >= 0) == (b >= 0) && (s >= 0) != (a >= 0))
}
-9223372036854775808
overflow: true
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
small,negative: sums far from the limits.beyond-32-bit: 9000000000 does not fit in 32 bits, but it fits in 64 bits.max-plus-zero,min-plus-zero: the limits themselves are valid sums.max-plus-one,max-plus-max: the sum is above the largest value.min-minus-one,min-plus-min: the sum is below the smallest value.min-plus-max,max-minus-one: operands with different signs never overflow, even at the limits.
Pitfalls
-
A test after the operation in C and C++. A test such as
if (a + b < a)computes the sum first. When the sum overflows, the behavior is already undefined1, and a compiler can remove the test. Use the test before the operation, or a builtin. The test after the operation is correct only where the wrap is defined, as in Go and Java. -
Negation and absolute value overflow too. The negative of the smallest value does not fit, because the range of a two's complement integer has one more negative value than positive values (see Two's complement). In C, "The unary minus invokes undefined behavior due to signed integer overflow when applied to INT_MIN, LONG_MIN, or LLONG_MIN"1. In Java, for
Math.abs(Long.MIN_VALUE)"the result is that same value, which is negative"8, andMath.absExactthrows an exception8:
This code runs but gives a wrong answer on purpose.
public class Main {
public static void main(String[] args) {
System.out.println(Math.abs(Long.MIN_VALUE));
System.out.println(-Long.MIN_VALUE);
try {
System.out.println(Math.absExact(Long.MIN_VALUE));
} catch (ArithmeticException e) {
System.out.println(e.getClass().getSimpleName());
}
}
}
-9223372036854775808
-9223372036854775808
ArithmeticException
- A JavaScript number loses precision before it overflows. Above 2 ** 53 - 1, a
numbercannot hold each integer, soa + 1anda + 2can give the same value with no error. UseNumber.isSafeIntegerto test a result, or useBigInt6:
This code runs but gives a wrong answer on purpose.
const a = Number.MAX_SAFE_INTEGER;
console.log(a + 1 === a + 2);
console.log(Number.isSafeInteger(a + 1));
console.log(BigInt(a) + 2n);
true
false
9007199254740993n
- Fixed-width types in Python wrap. A Python
intdoes not overflow, but the fixed-width types ofctypes,arrayand NumPy do. For thectypesinteger types, "no overflow checking is done"14:
This code runs but gives a wrong answer on purpose.
import ctypes
print(ctypes.c_int64(2**63).value)
print(ctypes.c_int8(200).value)
-9223372036854775808
-56
-
Each operation needs its own check. A check of the addition does not cover a multiplication. Use the checked form of each operation:
Math.multiplyExactin Java8,__builtin_mul_overflowin GCC9,checked_mulin Rust. A test before a multiplication is harder to write than a test before an addition, so prefer the library function. -
A wrong check of the result. Do not test
s < 0alone after the addition. A negative sum of two negative operands is correct. The sum overflowed only when the operands have the same sign and the sum has the other sign.
Related tasks
- Do integer arithmetic: the operators and their overflow rules.
- Detect division by zero: the other error of integer arithmetic.
- Use big integers: when a sum must not overflow at all.
See also the concepts Integer overflow behaviour, Two's complement and Integer representation.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/detect-integer-overflow/.
INT64_MIN = -(2**63)
INT64_MAX = 2**63 - 1
def checked_add(a: int, b: int) -> int | None:
"""Returns a + b, or None when the sum does not fit in 64 signed bits."""
# A Python int has no fixed width, so the sum is exact. Compare it with the
# range of the 64-bit type after the addition.
s = a + b
return s if INT64_MIN <= s <= INT64_MAX else None
test_checked_add.py 30 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/detect-integer-overflow/.
import pytest
from checked_add import INT64_MAX, INT64_MIN, checked_add
CASES = {
"small": (2, 3, 5),
"negative": (-7, 4, -3),
"beyond-32-bit": (4000000000, 5000000000, 9000000000),
"max-plus-zero": (INT64_MAX, 0, INT64_MAX),
"max-plus-one": (INT64_MAX, 1, None),
"max-plus-max": (INT64_MAX, INT64_MAX, None),
"min-plus-zero": (INT64_MIN, 0, INT64_MIN),
"min-minus-one": (INT64_MIN, -1, None),
"min-plus-min": (INT64_MIN, INT64_MIN, None),
"min-plus-max": (INT64_MIN, INT64_MAX, -1),
"max-minus-one": (INT64_MAX, -1, INT64_MAX - 1),
}
@pytest.mark.parametrize("case", CASES)
def test_checked_add(case):
a, b, want = CASES[case]
assert checked_add(a, b) == want
def test_limits():
assert INT64_MAX == 9223372036854775807
assert INT64_MIN == -9223372036854775808
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/detect-integer-overflow/.
#pragma once
#include <cstdint>
#include <limits>
#include <optional>
// checked_add returns a + b, or nothing when the sum does not fit in
// std::int64_t. A signed overflow is undefined behavior, so the function tests
// the operands before the addition.
constexpr std::optional<std::int64_t> checked_add(std::int64_t a, std::int64_t b) {
using limits = std::numeric_limits<std::int64_t>;
if ((b > 0 && a > limits::max() - b) || (b < 0 && a < limits::min() - b)) {
return std::nullopt;
}
return a + b;
}
test_checked_add.cpp 45 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/detect-integer-overflow/.
#include "checked_add.hpp"
#include <cstdio>
namespace {
constexpr auto MAX = std::numeric_limits<std::int64_t>::max();
constexpr auto MIN = std::numeric_limits<std::int64_t>::min();
// The function is constexpr, so the compiler can check it too.
static_assert(checked_add(MAX, 0) == MAX);
static_assert(!checked_add(MAX, 1).has_value());
int failures = 0;
void check(const char *label, std::int64_t a, std::int64_t b, std::optional<std::int64_t> want) {
if (checked_add(a, b) != want) {
std::fprintf(stderr, "case %s failed\n", label);
failures++;
}
}
} // namespace
int main() {
check("small", 2, 3, 5);
check("negative", -7, 4, -3);
check("beyond-32-bit", 4000000000, 5000000000, 9000000000);
check("max-plus-zero", MAX, 0, MAX);
check("max-plus-one", MAX, 1, std::nullopt);
check("max-plus-max", MAX, MAX, std::nullopt);
check("min-plus-zero", MIN, 0, MIN);
check("min-minus-one", MIN, -1, std::nullopt);
check("min-plus-min", MIN, MIN, std::nullopt);
check("min-plus-max", MIN, MAX, -1);
check("max-minus-one", MAX, -1, MAX - 1);
if (failures > 0) {
return 1;
}
std::printf("all cases pass\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/detect-integer-overflow/.
import java.util.OptionalLong;
final class CheckedAdd {
private CheckedAdd() {}
/** Returns a + b, or an empty OptionalLong when the sum does not fit in a long. */
static OptionalLong checkedAdd(long a, long b) {
try {
// Math.addExact throws ArithmeticException on overflow; a + b wraps.
return OptionalLong.of(Math.addExact(a, b));
} catch (ArithmeticException e) {
return OptionalLong.empty();
}
}
/** The same check with a test before the addition, with no exception. */
static OptionalLong checkedAddByTest(long a, long b) {
if ((b > 0 && a > Long.MAX_VALUE - b) || (b < 0 && a < Long.MIN_VALUE - b)) {
return OptionalLong.empty();
}
return OptionalLong.of(a + b);
}
}
CheckedAddTest.java 41 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/detect-integer-overflow/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.OptionalLong;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class CheckedAddTest {
static final long MAX = Long.MAX_VALUE;
static final long MIN = Long.MIN_VALUE;
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("small", 2L, 3L, OptionalLong.of(5)),
Arguments.of("negative", -7L, 4L, OptionalLong.of(-3)),
Arguments.of("beyond-32-bit", 4000000000L, 5000000000L, OptionalLong.of(9000000000L)),
Arguments.of("max-plus-zero", MAX, 0L, OptionalLong.of(MAX)),
Arguments.of("max-plus-one", MAX, 1L, OptionalLong.empty()),
Arguments.of("max-plus-max", MAX, MAX, OptionalLong.empty()),
Arguments.of("min-plus-zero", MIN, 0L, OptionalLong.of(MIN)),
Arguments.of("min-minus-one", MIN, -1L, OptionalLong.empty()),
Arguments.of("min-plus-min", MIN, MIN, OptionalLong.empty()),
Arguments.of("min-plus-max", MIN, MAX, OptionalLong.of(-1)),
Arguments.of("max-minus-one", MAX, -1L, OptionalLong.of(MAX - 1)));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void checkedAdd(String name, long a, long b, OptionalLong want) {
assertEquals(want, CheckedAdd.checkedAdd(a, b), name);
}
@ParameterizedTest(name = "{0} by test")
@MethodSource("cases")
void checkedAddByTest(String name, long a, long b, OptionalLong want) {
assertEquals(want, CheckedAdd.checkedAddByTest(a, b), name);
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/detect-integer-overflow/.
#include "checked_add.h"
bool checked_add(int64_t a, int64_t b, int64_t *out) {
#if defined(__GNUC__) || defined(__clang__)
// The builtin adds in infinite precision, stores the sum wrapped to 64
// bits and returns true when the stored value is not the exact sum.
return !__builtin_add_overflow(a, b, out);
#else
return checked_add_portable(a, b, out);
#endif
}
bool checked_add_portable(int64_t a, int64_t b, int64_t *out) {
// A signed overflow is undefined behavior, so do not compute a sum that
// overflows. Test the operands first: with b > 0 the sum overflows when
// a > INT64_MAX - b, and with b < 0 when a < INT64_MIN - b. Neither of
// these subtractions can overflow.
if ((b > 0 && a > INT64_MAX - b) || (b < 0 && a < INT64_MIN - b)) {
return false;
}
*out = a + b;
return true;
}
checked_add.h 18 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/detect-integer-overflow/.
#ifndef CHECKED_ADD_H
#define CHECKED_ADD_H
#include <stdbool.h>
#include <stdint.h>
// checked_add stores a + b in *out and returns true, or returns false when the
// sum does not fit in int64_t. It uses the GCC and Clang builtin.
bool checked_add(int64_t a, int64_t b, int64_t *out);
// checked_add_portable does the same in standard C, with a test before the
// addition.
bool checked_add_portable(int64_t a, int64_t b, int64_t *out);
#endif
test_checked_add.c 42 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/detect-integer-overflow/.
#include "checked_add.h"
#include <stdio.h>
static int failures = 0;
static void check(const char *label, int64_t a, int64_t b, bool want_ok, int64_t want) {
int64_t got = 0;
bool ok = checked_add(a, b, &got);
if (ok != want_ok || (ok && got != want)) {
fprintf(stderr, "case %s failed\n", label);
failures++;
}
got = 0;
ok = checked_add_portable(a, b, &got);
if (ok != want_ok || (ok && got != want)) {
fprintf(stderr, "case %s (portable) failed\n", label);
failures++;
}
}
int main(void) {
check("small", 2, 3, true, 5);
check("negative", -7, 4, true, -3);
check("beyond-32-bit", 4000000000, 5000000000, true, 9000000000);
check("max-plus-zero", INT64_MAX, 0, true, INT64_MAX);
check("max-plus-one", INT64_MAX, 1, false, 0);
check("max-plus-max", INT64_MAX, INT64_MAX, false, 0);
check("min-plus-zero", INT64_MIN, 0, true, INT64_MIN);
check("min-minus-one", INT64_MIN, -1, false, 0);
check("min-plus-min", INT64_MIN, INT64_MIN, false, 0);
check("min-plus-max", INT64_MIN, INT64_MAX, true, -1);
check("max-minus-one", INT64_MAX, -1, true, INT64_MAX - 1);
if (failures > 0) {
return 1;
}
printf("all cases pass\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/detect-integer-overflow/.
using System;
public static class Overflow
{
// Returns a + b, or null when the sum does not fit in a long. In a checked
// context an overflow throws OverflowException. The default context is
// unchecked, and there a + b wraps.
public static long? CheckedAdd(long a, long b)
{
try
{
return checked(a + b);
}
catch (OverflowException)
{
return null;
}
}
}
CheckedAddTests.cs 39 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/detect-integer-overflow/.
using Xunit;
public sealed class CheckedAddTests
{
private const long Max = long.MaxValue;
private const long Min = long.MinValue;
public static TheoryData<string, long, long, long?> Cases => new()
{
{ "small", 2, 3, 5 },
{ "negative", -7, 4, -3 },
{ "beyond-32-bit", 4000000000, 5000000000, 9000000000 },
{ "max-plus-zero", Max, 0, Max },
{ "max-plus-one", Max, 1, null },
{ "max-plus-max", Max, Max, null },
{ "min-plus-zero", Min, 0, Min },
{ "min-minus-one", Min, -1, null },
{ "min-plus-min", Min, Min, null },
{ "min-plus-max", Min, Max, -1 },
{ "max-minus-one", Max, -1, Max - 1 },
};
[Theory]
[MemberData(nameof(Cases))]
public void Check(string name, long a, long b, long? want)
{
Assert.NotNull(name);
Assert.Equal(want, Overflow.CheckedAdd(a, b));
}
[Fact]
public void UncheckedWraps()
{
long a = Max;
Assert.Equal(Min, unchecked(a + 1));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/detect-integer-overflow/.
// A number holds integers exactly only up to 2 ** 53 - 1, so 64-bit values
// are BigInt values. BigInt arithmetic is exact. BigInt.asIntN(64, s) keeps
// the low 64 bits of s as a signed value, so it changes s only when s does not
// fit in 64 bits.
export function checkedAdd(a, b) {
const s = a + b;
return BigInt.asIntN(64, s) === s ? s : null;
}
checked_add.test.js 33 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/detect-integer-overflow/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { checkedAdd } from "./checked_add.js";
const MAX = 9223372036854775807n;
const MIN = -9223372036854775808n;
const cases = [
["small", 2n, 3n, 5n],
["negative", -7n, 4n, -3n],
["beyond-32-bit", 4000000000n, 5000000000n, 9000000000n],
["max-plus-zero", MAX, 0n, MAX],
["max-plus-one", MAX, 1n, null],
["max-plus-max", MAX, MAX, null],
["min-plus-zero", MIN, 0n, MIN],
["min-minus-one", MIN, -1n, null],
["min-plus-min", MIN, MIN, null],
["min-plus-max", MIN, MAX, -1n],
["max-minus-one", MAX, -1n, MAX - 1n],
];
for (const [name, a, b, want] of cases) {
test(name, () => {
assert.equal(checkedAdd(a, b), want);
});
}
test("a BigInt and a number do not mix", () => {
assert.throws(() => checkedAdd(1n, 1), TypeError);
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/detect-integer-overflow/.
// A number holds integers exactly only up to 2 ** 53 - 1, so 64-bit values
// are bigint values. BigInt.asIntN(64, s) keeps the low 64 bits of s as a
// signed value, so it changes s only when s does not fit in 64 bits.
export function checkedAdd(a: bigint, b: bigint): bigint | null {
const s = a + b;
return BigInt.asIntN(64, s) === s ? s : null;
}
checked_add.test.ts 29 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/detect-integer-overflow/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { checkedAdd } from "./checked_add.ts";
const MAX = 9223372036854775807n;
const MIN = -9223372036854775808n;
const cases: [string, bigint, bigint, bigint | null][] = [
["small", 2n, 3n, 5n],
["negative", -7n, 4n, -3n],
["beyond-32-bit", 4000000000n, 5000000000n, 9000000000n],
["max-plus-zero", MAX, 0n, MAX],
["max-plus-one", MAX, 1n, null],
["max-plus-max", MAX, MAX, null],
["min-plus-zero", MIN, 0n, MIN],
["min-minus-one", MIN, -1n, null],
["min-plus-min", MIN, MIN, null],
["min-plus-max", MIN, MAX, -1n],
["max-minus-one", MAX, -1n, MAX - 1n],
];
for (const [name, a, b, want] of cases) {
test(name, () => {
assert.equal(checkedAdd(a, b), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/detect-integer-overflow/.
// Package overflow adds two int64 values and reports an overflow.
package overflow
// CheckedAdd returns a + b and true, or 0 and false when the sum does not fit
// in an int64.
func CheckedAdd(a, b int64) (int64, bool) {
// In Go a signed overflow is defined: the sum wraps and there is no panic.
// So compute the sum first and test it after. The sum overflowed when a
// and b have the same sign and the sum has the other sign.
s := a + b
if (a >= 0) == (b >= 0) && (s >= 0) != (a >= 0) {
return 0, false
}
return s, true
}
checked_add_test.go 49 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/detect-integer-overflow/.
package overflow
import (
"math"
"testing"
)
const (
max = math.MaxInt64
min = math.MinInt64
)
var cases = []struct {
name string
a, b int64
want int64
wantOK bool
}{
{"small", 2, 3, 5, true},
{"negative", -7, 4, -3, true},
{"beyond-32-bit", 4000000000, 5000000000, 9000000000, true},
{"max-plus-zero", max, 0, max, true},
{"max-plus-one", max, 1, 0, false},
{"max-plus-max", max, max, 0, false},
{"min-plus-zero", min, 0, min, true},
{"min-minus-one", min, -1, 0, false},
{"min-plus-min", min, min, 0, false},
{"min-plus-max", min, max, -1, true},
{"max-minus-one", max, -1, max - 1, true},
}
func TestCheckedAdd(t *testing.T) {
for _, c := range cases {
got, ok := CheckedAdd(c.a, c.b)
if got != c.want || ok != c.wantOK {
t.Errorf("%s: got (%d, %v), want (%d, %v)", c.name, got, ok, c.want, c.wantOK)
}
}
}
func TestPlusWraps(t *testing.T) {
a := int64(max)
if a+1 != min {
t.Errorf("max + 1 = %d, want %d", a+1, int64(min))
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/detect-integer-overflow/.
/// Returns a + b, or None when the sum does not fit in an i64.
pub fn checked_add(a: i64, b: i64) -> Option<i64> {
// a + b panics on overflow in a debug build and wraps in a release build.
// checked_add returns None in both.
a.checked_add(b)
}
tests/checked_add_test.rs 34 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/detect-integer-overflow/.
use algo_detect_integer_overflow::checked_add;
const MAX: i64 = i64::MAX;
const MIN: i64 = i64::MIN;
#[test]
fn cases() {
let cases: Vec<(&str, i64, i64, Option<i64>)> = vec![
("small", 2, 3, Some(5)),
("negative", -7, 4, Some(-3)),
("beyond-32-bit", 4000000000, 5000000000, Some(9000000000)),
("max-plus-zero", MAX, 0, Some(MAX)),
("max-plus-one", MAX, 1, None),
("max-plus-max", MAX, MAX, None),
("min-plus-zero", MIN, 0, Some(MIN)),
("min-minus-one", MIN, -1, None),
("min-plus-min", MIN, MIN, None),
("min-plus-max", MIN, MAX, Some(-1)),
("max-minus-one", MAX, -1, Some(MAX - 1)),
];
for (name, a, b, want) in cases {
assert_eq!(checked_add(a, b), want, "case {name}");
}
}
#[test]
fn other_overflow_methods() {
assert_eq!(MAX.wrapping_add(1), MIN);
assert_eq!(MAX.overflowing_add(1), (MIN, true));
assert_eq!(MAX.saturating_add(1), MAX);
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/detect-integer-overflow/.
# Bash arithmetic uses 64-bit signed integers with no check for overflow, so
# test the operands before the addition.
INT64_MAX=9223372036854775807
INT64_MIN=$((-9223372036854775807 - 1))
# checked_add A B
# Prints A + B, or prints nothing and returns status 1 when the sum does not
# fit in 64 bits.
checked_add() {
local a=$1 b=$2
if ((b > 0 && a > INT64_MAX - b)) || ((b < 0 && a < INT64_MIN - b)); then
return 1
fi
echo $((a + b))
}
test_checked_add.bats 33 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/detect-integer-overflow/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/checked_add.sh"
}
check() { # check WANT A B; WANT is none for no result
local want=$1 got status=0
shift
got=$(checked_add "$@") || status=$?
if [ "$want" = none ]; then
[ "$status" -ne 0 ] && [ -z "$got" ] || { printf 'got: %s\n' "$got"; return 1; }
else
[ "$status" -eq 0 ] && [ "$got" = "$want" ] || { printf 'got: %s\nwant: %s\n' "$got" "$want"; return 1; }
fi
}
@test "small" { check 5 2 3; }
@test "negative" { check -3 -7 4; }
@test "beyond-32-bit" { check 9000000000 4000000000 5000000000; }
@test "max-plus-zero" { check 9223372036854775807 9223372036854775807 0; }
@test "max-plus-one" { check none 9223372036854775807 1; }
@test "max-plus-max" { check none 9223372036854775807 9223372036854775807; }
@test "min-plus-zero" { check -9223372036854775808 -9223372036854775808 0; }
@test "min-minus-one" { check none -9223372036854775808 -1; }
@test "min-plus-min" { check none -9223372036854775808 -9223372036854775808; }
@test "min-plus-max" { check -1 -9223372036854775808 9223372036854775807; }
@test "max-minus-one" { check 9223372036854775806 9223372036854775807 -1; }
@test "plus wraps" { [ "$((INT64_MAX + 1))" = "$INT64_MIN" ]; }
References
- Arithmetic operators, C reference, cppreference.com, Overflows; Unary arithmetic, Notes
- The Go Programming Language Specification, Integer overflow
- The Java Language Specification, Java SE 27 Edition, Chapter 4: Types, Values, and Variables, 4.2.2 Integer Operations
- The checked and unchecked statements, C# reference, Microsoft Learn, the introduction
- Built-in Types, Python 3 documentation, Numeric Types, int, float, complex
- Number.isSafeInteger(), MDN Web Docs, Description
- BigInt.asIntN(), MDN Web Docs, Description
- Math, Java SE 27 API, addExact(long, long); multiplyExact(long, long); abs(long); absExact(long)
- Built-in Functions to Perform Arithmetic with Overflow Checking, Using the GNU Compiler Collection (GCC), __builtin_add_overflow; __builtin_mul_overflow
- ckd_add, C reference, cppreference.com, Return value
- i64, Rust standard library, checked_add; wrapping_add; overflowing_add; saturating_add
- Operator expressions, The Rust Reference, Overflow
- Bash Reference Manual, version 5.3, 6.5 Shell Arithmetic
- ctypes, A foreign function library for Python, Python 3 documentation, Fundamental data types, c_byte
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag XDABZC Edit this page History Report an error Markdown