JDK-8065313 : OutOfMemoryError in ByteArrayOutputStream.grow()
  • Type: Bug
  • Component: core-libs
  • Sub-Component: java.io
  • Affected Version: 7u40
  • Priority: P4
  • Status: Closed
  • Resolution: Duplicate
  • OS: windows_8
  • CPU: x86
  • Submitted: 2014-08-29
  • Updated: 2014-11-19
  • Resolved: 2014-11-19
Related Reports
Duplicate :  
Description
FULL PRODUCT VERSION :
java version "1.7.0_40"
Java(TM) SE Runtime Environment (build 1.7.0_40-b43)
Java HotSpot(TM) 64-Bit Server VM (build 24.0-b56, mixed mode)

ADDITIONAL OS VERSION INFORMATION :
Windows Server 2012 R2 Standard
Version	6.3.9600 Build 9600


A DESCRIPTION OF THE PROBLEM :
In my JDK ByteArrayOutputStream.grow() method uses Integer.MAX_VALUE as a maximum ByteArray value:

    /**
     * Increases the capacity to ensure that it can hold at least the
     * number of elements specified by the minimum capacity argument.
     *
     * @param minCapacity the desired minimum capacity
     */
    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = buf.length;
        int newCapacity = oldCapacity << 1;
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity < 0) {
            if (minCapacity < 0) // overflow
                throw new OutOfMemoryError();
            newCapacity = Integer.MAX_VALUE;
        }
        buf = Arrays.copyOf(buf, newCapacity);
    }

However, java could not create an array of such size, the maximum I can get is Integer.MAX_VALUE-2.

STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
run this code to get the error:
byte[] b = new byte[Integer.MAX_VALUE]

Run this code to be able to create a new ByteArray:
byte[] b = new byte[Integer.MAX_VALUE-2]

EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
no exception when growing array to a large size
ACTUAL -
exception

ERROR MESSAGES/STACK TRACES THAT OCCUR :
OutOfMemoryError: Requested array size exceeds VM limit

REPRODUCIBILITY :
This bug can be reproduced always.


Comments
This is a duplicate of JDK-8055949.
19-11-2014