Skip to content

Check Arithmetic Before It Overflows

The Course
•
24 min study

Go's integers have fixed sizes. An int32 holds values from -2147483648 to 2147483647, and when a result does not fit, it does not stop the program or report an error: it wraps around to the other end of the range. A stock count that silently turns negative is worse than a crash, because everything after it carries on with a wrong number. Any arithmetic on values that come from input needs a check, and the check has to be written so that it cannot overflow itself.

Most business values have a limit far below the machine's, such as the ledger's 10000 units per item. The same technique covers both kinds of limit.

Predict and run

Each variable starts at its type's maximum. What happens when one more is added?

Predict, then run Go
package main

import (
	"fmt"
	"math"
)

func main() {
	var small int8 = math.MaxInt8
	small++
	fmt.Println(small)

	var stock int32 = math.MaxInt32
	stock += 1
	fmt.Println(stock)

	var units uint8 = 0
	units--
	fmt.Println(units)
}
Check your prediction
Text
-128
-2147483648
255

The program ran to the end with three wrong answers and no warning. Signed integers wrap from the largest value to the smallest, and unsigned integers wrap from 0 to their maximum. Note that var small int8 = math.MaxInt8 + 1 does not compile, because Go checks constant values at compile time. Only values computed at run time wrap silently, and those are exactly the ones that come from input.

Check with subtraction, not addition

The obvious check, if have+n > limit, computes the sum first, and the sum is what might overflow. If have and n are both close to the maximum, have+n wraps to a negative number, which is less than the limit, and the check passes. Rearranging the comparison avoids that. When have is already within range, limit - have cannot overflow, and n > limit-have means exactly the same thing as have+n > limit.

A check that cannot overflow Go
package main

import (
	"errors"
	"fmt"
	"math"
)

var errOverflow = errors.New("sum would pass the limit")

func addNaive(have, n, limit int32) (int32, error) {
	if have+n > limit {
		return 0, errOverflow
	}
	return have + n, nil
}

func addChecked(have, n, limit int32) (int32, error) {
	if n > limit-have {
		return 0, errOverflow
	}
	return have + n, nil
}

func main() {
	big := int32(math.MaxInt32 - 5)
	fmt.Println(addNaive(big, 10, math.MaxInt32))
	fmt.Println(addChecked(big, 10, math.MaxInt32))
	fmt.Println(addChecked(9990, 10, 10000))
	fmt.Println(addChecked(9990, 11, 10000))
}
Text
-2147483644 <nil>
0 sum would pass the limit
10000 <nil>
0 sum would pass the limit

The naive version accepted a sum that wrapped to a large negative number. The checked version rejected it, and it also handles the business limit exactly: 9990 plus 10 reaches 10000 and is allowed, and one more is not. The project's addStock is this function with int and maxStock.

Where the checks belong

Check at the boundary where a value enters, and again wherever two trusted values are combined into a new one. In the ledger, the parser rejects any quantity outside 1 to 1000, so a single command can never be huge. That alone is not enough: stock grows across many commands, and a cancel returns stock that may have been topped up in the meantime. So addStock checks every addition, including the one inside Cancel. Subtraction needs a check too: the ledger never lets stock fall below zero, because Order compares each quantity with what is available before subtracting.

Bigger types move the problem

Switching from int32 to int64 makes overflow rarer, not impossible, and it hides the question of what the real limit is. Decide the limit your program promises, write it down as a constant, and check against it. The type only needs to be big enough to hold the limit.

Practice

Exercise

Your turn

Write applyDelta(have, delta int32) (int32, error), where delta may be positive or negative and the result must stay between 0 and math.MaxInt32. Return errOverflow for a result that is too large and errNegative for one below zero. Check MaxInt32 - 1 plus 1, plus 2, then 5 plus -5 and 5 plus -6.

The output should be:

Text
2147483647 <nil>
0 result would overflow
0 <nil>
0 result would be negative
Your working space Go
package main

func main() {
	// Write applyDelta, then check the four cases.
}
Hint 1: the idea

Handle the two signs separately. Only a positive delta can overflow, and only a negative delta can go below zero.

Hint 2: a first step

For a positive delta, compare delta > math.MaxInt32-have. For a negative one, compare -delta > have. Negating is safe here as long as delta is not math.MinInt32, so reject that value first.

Worked solution
Run the solution Go
package main

import (
	"errors"
	"fmt"
	"math"
)

var (
	errOverflow = errors.New("result would overflow")
	errNegative = errors.New("result would be negative")
)

func applyDelta(have, delta int32) (int32, error) {
	switch {
	case delta == math.MinInt32:
		return 0, errNegative
	case delta > 0 && delta > math.MaxInt32-have:
		return 0, errOverflow
	case delta < 0 && -delta > have:
		return 0, errNegative
	}
	return have + delta, nil
}

func main() {
	top := int32(math.MaxInt32 - 1)
	fmt.Println(applyDelta(top, 1))
	fmt.Println(applyDelta(top, 2))
	fmt.Println(applyDelta(5, -5))
	fmt.Println(applyDelta(5, -6))
}
Text
2147483647 <nil>
0 result would overflow
0 <nil>
0 result would be negative

Both edges are checked from each side: the maximum is reachable and one past it is not, and zero is reachable and one below it is not. -math.MinInt32 would itself overflow, which is why that single value is rejected before anything is negated.

Was this article helpful?

Your response is saved on this device.