libgcj/8481: java.Random.nextInt(int) may return negative

svens@it.uu.se svens@it.uu.se
Wed Nov 6 09:46:00 GMT 2002


>Number:         8481
>Category:       libgcj
>Synopsis:       java.Random.nextInt(int) may return negative
>Confidential:   no
>Severity:       non-critical
>Priority:       low
>Responsible:    unassigned
>State:          open
>Class:          sw-bug
>Submitter-Id:   net
>Arrival-Date:   Wed Nov 06 09:46:02 PST 2002
>Closed-Date:
>Last-Modified:
>Originator:     Sven Sandberg
>Release:        gcc 3.2 (or CVS from 2002-11-06)
>Organization:
>Environment:
The bug is independent of envionment.
>Description:
java.Random.nextInt(int) has a typo that makes it return negative in some (apparantly rare) cases. To get the next random number, it calls the protected method java.Random.next(int) with the parameter 32, but it should be 31 (both to be correct and according to the specification at http://java.sun.com/j2se/1.4.1/docs/api/java/util/Random.html#nextInt(int). 
(Moreover, even if you are lucky and never exploit the bug, it does not yield the same sequence of random numbers for a given seed as Sun's implementation.)
>How-To-Repeat:
The attached file exploits the bug and prints:
i=867384, x=-222
>Fix:
Here's a patch against a recent CVS:

Index: libjava/java/util/Random.java
===================================================================
RCS file: /cvsroot/gcc/gcc/libjava/java/util/Random.java,v
retrieving revision 1.7
diff -u -r1.7 Random.java
--- libjava/java/util/Random.java       18 Jun 2002 15:40:00 -0000      1.7
+++ libjava/java/util/Random.java       6 Nov 2002 16:55:16 -0000
@@ -296,7 +296,7 @@
     int bits, val;
     do
       {
-        bits = next(32);
+        bits = next(31);
         val = bits % n;
       }
     while (bits - val + (n - 1) < 0);
>Release-Note:
>Audit-Trail:
>Unformatted:
----gnatsweb-attachment----
Content-Type: application/octet-stream; name="Test.java"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="Test.java"

aW1wb3J0IGphdmEudXRpbC5SYW5kb207CnB1YmxpYyBjbGFzcyBUZXN0IHsKICAgIHB1YmxpYyBz
dGF0aWMgdm9pZCBtYWluKFN0cmluZ1tdIGFyZ3MpIHsKCVJhbmRvbSByPSBuZXcgUmFuZG9tKDAp
OwoJZm9yIChpbnQgaT0wOyBpPDEwMDAwMDA7IGkrKykgewoJICAgIGludCB4ID0gci5uZXh0SW50
KDEwMDApOwoJICAgIGlmICgoeCA8IDApIHx8ICh4ID49IDEwMDApKQoJCVN5c3RlbS5vdXQucHJp
bnRsbigiaT0iK2krIiwgeD0iK3gpOwoJfQogICAgfQp9Cg==



More information about the Gcc-bugs mailing list