Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix "integer overflow" bug. #2

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

lbolla
Copy link

@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.

@silentmatt
Copy link

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.

@nzakas
Copy link
Collaborator

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants