JDK-8029784 : (str) StringBuilder and StringBuffer fail when initialized with large strings
  • Type: Bug
  • Component: core-libs
  • Sub-Component: java.lang
  • Affected Version: 7u45
  • Priority: P4
  • Status: Closed
  • Resolution: Duplicate
  • OS: windows_xp
  • Submitted: 2013-12-06
  • Updated: 2019-03-17
  • Resolved: 2019-03-17
The Version table provides details related to the release that this issue/RFE will be addressed.

Unresolved : Release in which this issue/RFE will be addressed.
Resolved: Release in which this issue/RFE has been resolved.
Fixed : Release in which this issue/RFE has been fixed. The release containing this fix may be available for download as an Early Access Release or a General Availability Release.

To download the current JDK release, click here.
Other
tbd_majorResolved
Related Reports
Duplicate :  
Relates :  
Description
FULL PRODUCT VERSION :


A DESCRIPTION OF THE PROBLEM :
The initial capacity of a StringBuilder/Buffer when initialized with an existing String or CharSequence is the length of the original text + 16. If the original length is close to Integer.MAX_VALUE, the addition causes the sum to become negative and the allocation throws a NegativeArraySizeException.

Consequently, Strings begin to malfunction before they reach their theoretical maximum length, because you can't append to them with `+` or `+=` any more.

Original code in StringBuilder and StringBuffer:

    super(str.length() + 16);

  Suggested fix:

    super((int)Math.min(Integer.MAX_VALUE, str.length() + 16L));

Likewise for the CharSequence constructors.


REPRODUCIBILITY :
This bug can be reproduced always.
Comments
The different String internal representations (currently ISO-LATIN-1 and UTF-16) have different maximum lengths. The impact of this will need to be examined.
15-12-2017

These constructors specify that they use an initial capacity of length + 16 so that should be looked at too.
08-12-2013