Is it possible for the property "length" of an array to overflow?

Viewed 46

Let's say a highly sensitive codebase has the following check:

  public Something(byte[] content) {
        if (content.length != 20) {
            throw new RuntimeException("length is invalid");
        }
         
        // do something critical with content

And the constructor Something is called like this:

ByteArrayOutputStream a = new ByteArrayOutputStream();

// fill the byte array as you want
...

// call the highly sensitive constructor
Something(a.toByteArray());

Is it possible -granted enough memory- to fill the ByteArrayOutputStream with 2*Integer.MAX_VALUE + 20, so that the comparison of the array's length with 20 is valid?

I have found this article about the theoretical limit of array lengths upon their creation, but I wonder if there is an edge case when converting from unbounded data structure like ... or streams to byte arrays (like returned by the toByteArray of ByteArrayOutputStream class).

1 Answers

I wonder if there is an edge case when converting from unbounded data structure like String or streams to byte arrays (like returned by the toByteArray of ByteArrayOutputStream class).

The premise of the question is flawed, because these aren't unbounded data structures. Both of these are basically just wrappers around arrays (char[] and byte[], respectively), so they are subject to the limitations of arrays.

An array's length is an int, and is baked in at array creation time. As such, if you create an array with length calculation with an overflow, the array's length will be that int's value. You can't create an array with a long length, nor can you access one of its elements with a long index.

In other words, if an array says that its length is 20, its length is 20.

Related