Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8206403

ByteArrayOutputStream hugeCapacity method can return invalid capacity

    XMLWordPrintable

    Details

    • Subcomponent:
    • CPU:
      generic
    • OS:
      generic

      Description

      A DESCRIPTION OF THE PROBLEM :
      private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
          
      private static int hugeCapacity(int minCapacity) {
            if (minCapacity < 0) // overflow
                throw new OutOfMemoryError();
            return (minCapacity > MAX_ARRAY_SIZE) ?
                Integer.MAX_VALUE :
                MAX_ARRAY_SIZE;

      The maximum size of an array the VM lets create is Integer.MAX_VALUE - 2. (2147483645)
      The MAX_ARRAY_SIZE constant's value is Integer.MAX_VALUE - 8. (2147483639)

      So any value between the two will result in hugeCapacity function to return Integer.MAX_VALUE.
      Which value is too high so it will cause an OutOfMemoryError.

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
          byte[] buf = new byte[Integer.MAX_VALUE-6];
          ByteArrayOutputStream out = new ByteArrayOutputStream(1);
          out.write(buf);

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      The underlaying array in the ByteArrayOutputStream can be the same size as buff variable.
      ACTUAL -
      Exception in thread "main" java.lang.OutOfMemoryError: Requested array size exceeds VM limit
      at java.util.Arrays.copyOf(Arrays.java:3236)
      at java.io.ByteArrayOutputStream.grow(ByteArrayOutputStream.java:118)
      at java.io.ByteArrayOutputStream.ensureCapacity(ByteArrayOutputStream.java:93)
      at java.io.ByteArrayOutputStream.write(ByteArrayOutputStream.java:153)
      at java.io.OutputStream.write(OutputStream.java:75)
      at com.company.Main.main(Main.java:17)

      ---------- BEGIN SOURCE ----------
      package com.company;

      import java.io.ByteArrayOutputStream;
      import java.io.IOException;

      public class Main {
        public static void main(String[] args) throws IOException {
          byte[] buf = new byte[Integer.MAX_VALUE-6];
          ByteArrayOutputStream out = new ByteArrayOutputStream(1);
          out.write(buf);
        }
      }
      ---------- END SOURCE ----------

      FREQUENCY : always


        Attachments

          Issue Links

            Activity

              People

              Assignee:
              bpb Brian Burkhalter
              Reporter:
              webbuggrp Webbug Group
              Votes:
              0 Vote for this issue
              Watchers:
              5 Start watching this issue

                Dates

                Created:
                Updated:
                Resolved: