Fix "integer overflow" bug. #2

Open
wants to merge 1 commit into
from

Projects

None yet

3 participants

@lbolla
lbolla commented Jun 13, 2011

If stopIndex+startIndex is greater than the greatest integer allowed by the language, then (stopIndex + startIndex) will overflow.
One way to fix this is to rewrite the average as:
(stopIndex + startIndex)/2 == startIndex + (stopIndex - startIndex)/2

startIndex + (stopIndex - startIndex)/2 never overflows, as it is always strictly less than stopIndex and so is any intermediate result of the computation.

This isn't actually an issue in JavaScript, since array indexes are 32-bit integers and numbers are double-precision floating point numbers (with 53 bits of precision). Any stopIndex and startIndex that would overflow (or really, just lose precision) are already way beyond the maximum array length.

It still might be worth changing for teaching purposes since it is a bug in C/C++/Java/etc.

Owner
nzakas commented Jun 13, 2011

If you add a comment above it explaining why you're doing it this way, I'll merge it in.

@lbolla
Owner
lbolla commented on e37d184 Jun 15, 2011

If stopIndex+startIndex is greater than the greatest integer allowed by the language, then (stopIndex + startIndex) will overflow.
One way to fix this is to rewrite the average as:
(stopIndex + startIndex)/2 == startIndex + (stopIndex - startIndex)/2

startIndex + (stopIndex - startIndex)/2 never overflows, as it is always strictly less than stopIndex and so is any intermediate result of the computation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment