cushon / issues-import

0 stars 0 forks source link

Math.abs followed by modulus. #247

Closed cushon closed 9 years ago

cushon commented 9 years ago

Original issue created by dmbrown@google.com on 2014-04-04 at 07:32 PM


Taking absolute value of a number followed by a modulus. This pattern is common, for example, for inserting values into hashtables. Math.abs(Integer.MIN_VALUE) returns Integer.MIN_VALUE, and the subsequent modulus returns a negative value. This is almost always undesirable, as the intent is typically to get a value between 0 and modulus-1, and this bug can cause runtime errors of the result is used as an array index. This issue is easily fixed by taking the modulus first.

Incorrect Pattern: Math.abs(value) % modulus

Correction: Maht.abs(value % modulus)

Examples:

https://cs.corp.google.com/#search/&q=Math.abs%5C(.*%5C.hashCode%5C(%5C)%5C)%5C%20%25%5C%20.*%5C)&sq=package:%5Epiper$%20-file:%5E//depot/google3/experimental%20file:%5E//depot/google3/&type=cs&m=100&det=matsel

cushon commented 9 years ago

Original comment posted by eaftan@google.com on 2014-04-07 at 10:15 PM


(No comment entered for this change.)


Status: Duplicate Merged Into: #77