Logic and arithmetic bugs: code breaks at the edges, not in the middle
18 min read
Suppose the post list shows 10 posts per page, and the code computes the number of pages like this:
pages := total / perPage // 101 / 10 = 10
The test uses 100 posts and gets 10 pages, which is correct. The system runs in production for months. On the day post 101 arrives, the code still returns 10 pages. The newest post disappears from the list. Nothing returns an error, and nothing crashes.
The map of software bugs puts bugs like this in group 1, logic and arithmetic. The code does exactly what it says, and what it says is wrong. The previous article explained why the same groups of bugs come back, even from experienced programmers. This article looks at group 1 in detail. The question is this: why does code that worked a thousand times fail on the thousand-and-first?
Bugs in this group live at the edges
The short answer is that middle values almost never break. Edge values do. Most logic and arithmetic bugs sit at one of three kinds of edge:
| Edge | Examples |
|---|---|
| The edge of a range | The first item, the last item, an empty range, a page that is not full |
| The edge of a number type | The largest int32, the precision of float64 |
| The edge between units or meanings | Seconds and nanoseconds, baht and satang, an enum value added later |
When we write code, we think about the usual case. When we write tests, we pick usual values too, such as 100 posts or a price of 250 baht. Edge values are rare in real use. This is the mechanism that the previous article called "no feedback, no experience". A programmer with ten years of experience may never have seen a number large enough to overflow an int32.
Testing has had a name for this for a long time. In The Art of Software Testing (1979), Glenford Myers describes boundary value analysis as one of the most useful ways to design tests. You pick test values at the edges and next to them on both sides, instead of values in the middle.
The rest of this article goes through the edges one at a time. Each one has a real incident and something that guards the edge in place of human attention.
Count the posts, not the gaps
A fence is 100 meters long, with a post every 10 meters. How many posts do you need? The first answer that comes to mind is usually 10. The correct answer is 11, because there is a post at each end. This kind of bug is called a fencepost error, or off-by-one: you count the gaps when you need the posts, or the posts when you need the gaps.
The pagination code above is a fencepost error. 101 posts at 10 per page must round up to 11 pages, but integer division in Go drops the remainder.
Most languages reduce this group of bugs by choosing a good way to write ranges. Edsger Dijkstra wrote a short note called Why numbering should start at zero (EWD831, 1982). It compares four ways to write the numbers 2 to 12 and concludes that 2 ≤ i < 13 is the best. This form is a half-open range. It includes the lower bound and excludes the upper bound. It has three advantages:
- The length of the range is
upper - lower, with no plus or minus one. - An empty range is easy to write. The lower bound equals the upper bound.
- Adjacent ranges share a bound.
[0, 10)followed by[10, 20)repeats no item and skips no item.
Go slices use this form. items[start:end] runs from start up to, but not including, end. This site's pagination function in internal/core/listing uses both rounding up and a half-open range:
func Paginate[T any](items []T, n, perPage int) (Page[T], error) {
if perPage < 1 {
perPage = 1
}
total := max(1, (len(items)+perPage-1)/perPage) // round up; an empty list still has 1 page
if n < 1 || n > total {
return Page[T]{}, ErrPageOutOfRange
}
start := (n - 1) * perPage
end := min(start+perPage, len(items)) // the last page may not be full
return Page[T]{Items: items[start:end], Number: n, Total: total}, nil
}
Almost every line of this function handles an edge: a perPage of zero, an empty list, page zero, a page past the last page, and a last page that is not full. To find out whether a function's author thought about edges, read the names of its tests. The tests for Paginate are named first, middle, last partial, exact fit, empty has one page, past end, and zero. Only middle is a middle value.
Numbers in a computer have edges. Numbers in math do not
In math, (a + b) / 2 always lies between a and b. In int32, it does not.
In 2006, Joshua Bloch wrote on the Google Research blog that the binary search he wrote for java.util.Arrays had a bug in this line:
int mid = (low + high) / 2;
When an array has 2^30 elements (about a billion) or more, low + high can exceed the largest int and become negative. The bug sat in the JDK for about nine years before someone hit it. The binary search that Jon Bentley proved correct in the book Programming Pearls has the same bug. The proof used numbers from math, which have no edges.
Here is the same bug in Go, with int32 so that it overflows sooner:
var lo, hi int32 = 1_500_000_000, 2_000_000_000
fmt.Println((lo + hi) / 2) // -397483648
fmt.Println(lo + (hi-lo)/2) // 1750000000
The fix computes the distance first and then adds it back. hi - lo cannot overflow when both values are non-negative indexes. Go's standard library guards against this bug too. sort.Search has this line:
h := int(uint(i+j) >> 1) // avoid overflow when computing h
The Go compiler catches overflow only in constants. A value computed at run time wraps around without a sound:
var big int32 = 3_000_000_000
// cannot use 3_000_000_000 (untyped int constant 3000000000) as int32 value
// in variable declaration (overflows)
Another edge appears when you convert between number types. A value too large for the target type loses its high bits, with no error:
var bh int64 = 40000
fmt.Println(int16(bh)) // -25536
n := 300
fmt.Println(uint8(n)) // 44
The first Ariane 5 flight, on 4 June 1996, broke up about 39 seconds after liftoff for this reason. The inquiry board's report says that the inertial reference software converted a 64-bit floating-point value called BH (horizontal bias) to a 16-bit signed integer. The value was larger than 16 bits can hold, so the conversion raised an Operand Error. The main and backup inertial reference systems stopped working almost at the same time.
The reason the conversion had no protection is the interesting part. The software came from Ariane 4. The team protected some conversions and left three variables unprotected, BH among them. Their analysis said that the values were physically limited or had a large safety margin. That reasoning was correct for Ariane 4. Ariane 5 flies with a higher horizontal velocity, so BH grew larger than anyone expected. The function that computed BH served no purpose after liftoff, but the team kept it for commonality with the old system. This is the rule-based mistake from the previous article: a rule that used to be right, applied where it no longer is.
A float is an approximation
float64 cannot store 0.1 exactly, because 0.1 in binary is an endless fraction, like 1/3 in decimal.
a, b := 0.1, 0.2
fmt.Println(a+b == 0.3, a+b) // false 0.30000000000000004
sum := 0.0
for range 10 {
sum += 0.1
}
fmt.Println(sum, sum == 1.0) // 0.9999999999999999 false
One detail confuses Go programmers. If you write 0.1+0.2 == 0.3 with constants only, the result is true. The compiler evaluates constants with much more precision than float64 has. A test that uses constants passes, while the real code, which computes with variables, gets a different result.
Each error is tiny, but the errors add up. The clearest incident is the Patriot missile system in the Gulf War. The GAO report (IMTEC-92-26) explains that the system counted time in tenths of a second and converted it to seconds with a 24-bit register. The value 1/10, cut down to 24 bits, was slightly wrong, and the error grew with every tick of the clock. The longer the system ran, the larger the error became.
I repeated the calculation, cutting 0.1 to 23 binary fraction digits as that register did:
const scale = 1 << 23
tenth := 0.1
chopped := float64(int64(tenth*scale)) / scale
ticks := 100 * 3600 * 10 // 100 hours, counted in tenths of a second
fmt.Printf("%.10f %.4f\n", tenth-chopped, float64(ticks)*(tenth-chopped))
// 0.0000000954 0.3433
The result is 0.3433 seconds, the same value as the GAO table for a system that ran for 100 hours without a restart. The same table says that this error moved the range the system searched for a target by about 687 meters. On 25 February 1991, the system at Dhahran had been running for more than 100 hours. It failed to track and intercept a Scud missile, which hit an Army barracks and killed 28 American soldiers. The corrected software reached Dhahran the next day.
The error per tick is 0.0000000954 seconds. No test that runs for a few seconds can see it. It shows up only at the edge of running time.
Money is where floats cause bugs most often. Three items at 0.1 baht each add up to 0.30000000000000004. That is why this project's AGENTS.md says that money is int64 minor units plus a currency code, never float64. The Opengrep rule money-as-float in .opengrep/conventions.yaml fails the build as soon as a struct has a float64 field named price, total, amount, cost, fee, or balance.
A number without a unit
time.Sleep(5) // sleeps for 5 nanoseconds, not 5 seconds
In many languages, the sleep function takes seconds or milliseconds. A programmer who comes from one of those languages can easily write this line. Go's time.Sleep takes a time.Duration, which counts nanoseconds.
Go's advantage is that the unit is part of the type. time.Duration(5) prints as 5ns. The correct form reads aloud exactly as it means:
time.Sleep(5 * time.Second)
A bare constant such as 5 still compiles, because Go converts untyped constants to the type it needs. Staticcheck has a check, SA1004, for exactly this case, and golangci-lint enables staticcheck by default:
main.go:30:13: SA1004: sleeping for 5 nanoseconds is probably a bug; be explicit if it isn't (staticcheck)
The largest incident of this kind is the Mars Climate Orbiter, which is already in the map of software bugs. One team's software produced pound-force seconds, and another team read the values as newton-seconds. Both sides used plain double values, so nothing said that the units were different.
The lesson is that when a number has a unit, the unit belongs in the type, not in a variable name or in someone's head. time.Duration is the best example in the standard library. Money in this system should get its own type for the same reason.
The order your eyes see and the order the compiler sees
Read this C code:
int x = 6;
if (x & 1 == 0) {
printf("even\n");
} else {
printf("odd?\n");
}
The program prints odd?. In C, == binds tighter than &. The condition is x & (1 == 0), which is x & 0, which is always false. clang warns about this with -Wall:
prec.c:5:11: warning: & has lower precedence than ==; == will be evaluated first [-Wparentheses]
Go fixed this in the language design. In Go, & binds tighter than ==, so x&1 == 0 means what a reader sees, and it is true for x = 6. This is the same approach Go took to goto fail in the previous article. It makes what people see match what the machine does, without relying on anyone's attention.
Boolean logic goes wrong in the same way. The condition user.role == "admin" or "editor" from the start of the bug map is one example. Another common one is to negate !(a && b) as !a && !b, which is wrong. By De Morgan's law, the correct negation is !a || !b.
A new value the switch does not know
Another edge appears over time. A system has three order statuses, and later someone adds a fourth:
type Status int
const (
Pending Status = iota
Paid
Shipped
Refunded // added later
)
func label(s Status) string {
switch s {
case Pending:
return "awaiting payment"
case Paid:
return "paid"
case Shipped:
return "shipped"
}
return "" // Refunded ends up here, and the screen shows a blank
}
The person who added Refunded changed the file that declares the constants. They did not change every switch in other files. The Go compiler does not require a switch to cover every value. A linter called exhaustive catches this, but you have to enable it, because golangci-lint does not enable it by default:
main.go:18:2: missing cases in expression switch: Refunded (exhaustive)
Turn a bug that bit you into a rule
General linters have no check for (lo + hi) / 2, because in most code it is not a bug. If your team was bitten by this bug once, a way to stop it from coming back is to write an Opengrep rule, as the article on Opengrep explains. Here is the first version of the rule:
rules:
- id: midpoint-overflow
languages: [go]
severity: WARNING
message: >-
($LO + $HI) can overflow when both are large. Write $LO + ($HI-$LO)/2.
pattern-either:
- pattern: ($LO + $HI) / 2
- pattern: ($LO + $HI) >> 1
This rule catches (lo + hi) / 2. It also catches (price + tax) / 2, which is not the midpoint of two indexes. A rule that often reports false matches becomes a signal that is always on, and the team learns to ignore it. The second version matches only variable names that mark the bounds of a range:
patterns:
- pattern-either:
- pattern: ($LO + $HI) / 2
- pattern: ($LO + $HI) >> 1
- metavariable-regex:
metavariable: $LO
regex: (?i)^(lo|low|left|start|begin|first)$
The fixture file has // ruleid: midpoint-overflow above the code that the rule must catch, and // ok: midpoint-overflow above lo + (hi-lo)/2 and (price + tax) / 2, which it must not catch. opengrep test reports 1/1: ✓ All tests passed. When I ran the rule on internal and cmd in this repository, it found nothing. Every rule in this article was run with Opengrep 1.26.0.
Tests must check the edges
Tools catch only the patterns that someone wrote a rule for. An off-by-one error in the logic of a specific task has no fixed pattern. Tests are still the main guard for this group, and a test finds the bug only if it picks values at the edge:
func Mid(lo, hi int32) int32 {
return (lo + hi) / 2
}
func TestMid(t *testing.T) {
tests := []struct{ lo, hi, want int32 }{
{0, 0, 0}, // the smallest range
{0, 1, 0}, // two items
{4, 10, 7}, // an ordinary middle
{0, math.MaxInt32, math.MaxInt32 / 2},
{math.MaxInt32 - 1, math.MaxInt32, math.MaxInt32 - 1}, // the top of int32
}
for _, tt := range tests {
if got := Mid(tt.lo, tt.hi); got != tt.want {
t.Errorf("Mid(%d, %d) = %d, want %d", tt.lo, tt.hi, got, tt.want)
}
}
}
--- FAIL: TestMid (0.00s)
edge_test.go:18: Mid(2147483646, 2147483647) = -1, want 2147483646
The first four rows pass. Only the last row finds the bug. After the fix to lo + (hi-lo)/2, every row passes.
Fuzzing helps, but it has limits. I wrote a fuzz test that checks that Mid always lies between lo and hi, and started it from the seed (0, 10). Go's fuzzer ran for 30 seconds on my machine and did not find this bug. When I added an edge seed, f.Add(int32(math.MaxInt32-1), int32(math.MaxInt32)), the test failed at once, on the first run. A fuzzer does not know where the edges of your code are unless you tell it.
Agents write the middle too
A model learns from existing code, and (low + high) / 2 appears in a huge number of textbooks and code samples. The same is true of prices stored as float64. The most common form is the first form an agent writes. The tests that an agent writes for itself also tend to pick middle values, as people do.
The good news is that an agent gets output from staticcheck, exhaustive, and Opengrep rules within seconds of editing a file, and fixes the code right away. For edge tests, tell the agent directly that you need cases for empty, one item, the maximum value, and a page that is not full. Then read the test table it produces and check that it covers them, as the article on reading code recommends.
A table to keep
| Bug | The edge it hides at | Why it recurs | What guards the edge |
|---|---|---|---|
| Off-by-one | The first item, the last item, an empty range, a page that is not full | We think and test with middle values | Half-open ranges, correct rounding up, and tests at the edges |
| Integer overflow | The largest value of the type | Large values never appear during development | lo + (hi-lo)/2, tests with math.MaxInt32, and the team's Opengrep rule |
| Conversion that drops bits | A value larger than the target type | A rule that was right in the old system | A range check before the conversion, and no conversion that is not needed |
| Floating point | Float precision and accumulated error | The error is too small to see in a short test | int64 minor units for money, the money-as-float rule, and no == on floats |
| Unit mismatch | The seam between two pieces of code | A bare number does not carry its unit | Types with units, such as time.Duration, and staticcheck SA1004 |
| Operator precedence and boolean logic | What the eye sees versus what the compiler does | The eye reads meaning, not tokens | Languages designed to match, -Wall, and parentheses |
| Incomplete switch | An enum value added later | The person who adds a value does not see every switch | The exhaustive linter |
What to do differently
Before you write the tests for any function, list its edges: empty, one item, an exact fit, one past the end, the maximum value, negative values, the unit of every number, and every enum value. Then ask what guards each edge: a type, a linter, an Opengrep rule, or a test. If the answer is "the author will be careful", that edge is where the next bug will appear.
The next article in this series covers group 2: null, state, and data. That group is where the type system helps the most, if your language supports it.
References
- Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken (Joshua Bloch, Google Research blog, 2006): the
(low + high) / 2bug in the JDK and in Programming Pearls - Why numbering should start at zero (Edsger W. Dijkstra, EWD831, 1982): the case for half-open ranges
- Glenford J. Myers, The Art of Software Testing (Wiley, 1979): boundary value analysis
- Ariane 5 Flight 501 Failure, Report by the Inquiry Board (inquiry board chaired by J. L. Lions, 1996): the conversion of BH from 64 bits to 16 bits
- Patriot Missile Defense: Software Problem Led to System Failure at Dhahran, Saudi Arabia (GAO, IMTEC-92-26, 1992): the 0.3433-second time error after 100 hours
- Mars Climate Orbiter team finds likely cause of loss (JPL, 1999)
- SA1004 (staticcheck): catches
time.Sleepcalled with a suspiciously small constant - exhaustive: a linter that checks that a switch covers every enum value
- The Go Programming Language Specification: Operator precedence: the order of
&and==in Go