Arrays.copyOfRange: insufficient range checks
Tagir Valeev
amaembo at gmail.com
Mon Jan 26 14:08:52 UTC 2026
Hello!
A friend of mine noticed that bounds checks in every overload of
Arrays.copyOfRange are not enough. It checks only the following [1]:
int newLength = to - from;
if (newLength < 0) {
throw new IllegalArgumentException(from + " > " + to);
}
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:
void main() {
byte[] arr = new byte[2_000_000_000];
byte[] arr2 = Arrays.copyOfRange(arr, 2_000_000_000, Integer.MIN_VALUE);
IO.println(arr2.length);
}
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.
Does anybody want to take a look at this problem?
With best regards,
Tagir Valeev
[1]
https://github.com/openjdk/jdk/blob/512f95cf2632167149e2118853ab4d6d636fe0a3/src/java.base/share/classes/java/util/Arrays.java#L3845
[2] https://bugs.openjdk.org/browse/JDK-6530897
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/core-libs-dev/attachments/20260126/4f2ae581/attachment-0001.htm>
More information about the core-libs-dev
mailing list