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.
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.
- duplicates
-
JDK-8218227 StringBuilder/StringBuffer constructor throws confusing NegativeArraySizeException
-
- Resolved
-
- relates to
-
JDK-8149330 Capacity of StringBuilder should not get close to Integer.MAX_VALUE unless necessary
-
- Resolved
-