<div dir="ltr">Hello!<div><br></div><div>A friend of mine noticed that bounds checks in every overload of Arrays.copyOfRange are not enough. It checks only the following [1]:</div><div><br></div><div>        int newLength = to - from;<br>        if (newLength < 0) {<br>            throw new IllegalArgumentException(from + " > " + to);<br>        }</div><div><br></div><div>However, a subtraction overflow is possible, which may make newLength positive. I've found an abandoned issue JDK-6530897 [2], which discusses this problem. What's not mentioned there is that the method may not only throw a wrong exception but may also finish successfully (given enough heap space) for obviously incorrect arguments. For example, consider the following code:</div><div><br></div><div>void main() {<br>  byte[] arr = new byte[2_000_000_000];<br>  byte[] arr2 = Arrays.copyOfRange(arr, 2_000_000_000, Integer.MIN_VALUE);<br>  IO.println(arr2.length);<br>}</div><div><br></div><div>On my machine, with openjdk build 25+36-3489 it's executed successfully and prints 147483648. According to the specification, it should throw IllegalArgumentException, as from is greater than to.</div><div><br></div><div>Does anybody want to take a look at this problem?</div><div><br></div><div>With best regards,</div><div>Tagir Valeev</div><div><br></div><div>[1] <a href="https://github.com/openjdk/jdk/blob/512f95cf2632167149e2118853ab4d6d636fe0a3/src/java.base/share/classes/java/util/Arrays.java#L3845">https://github.com/openjdk/jdk/blob/512f95cf2632167149e2118853ab4d6d636fe0a3/src/java.base/share/classes/java/util/Arrays.java#L3845</a></div><div>[2] <a href="https://bugs.openjdk.org/browse/JDK-6530897">https://bugs.openjdk.org/browse/JDK-6530897</a></div></div>