Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when a Java String overflows?

As far as I understand, Java Strings are just an array of characters, with the maximum length being an integer value. If I understand this answer correctly, it is possible to cause an overflow with a String - albeit in "unusual circumstances".

Since Java Strings are based on char arrays and Java automatically checks array bounds, buffer overflows are only possible in unusual scenarios:

  1. If you call native code via JNI
  2. In the JVM itself (usually written in C++)
  3. The interpreter or JIT compiler does not work correctly (Java bytecode mandated bounds checks)

Correct me if I'm wrong, but I believe this means that you can write outside the bounds of the array, without triggering the ArrayIndexOutOfBounds (or similar) exception.

I've encountered issues in C++ with buffer overflows, and I can find plenty of advice about other languages, but none specifically answering what would happen if you caused a buffer overflow with a String (or any other array type) in Java.

I know that Java Strings are bounds-checked, and can't be overflowed by native Java code alone (unless issues are present in the compiler or JVM, as per points 2 and 3 above), but the first point implies that it is technically possible to get a char[] into an... undesirable position.

Given this, I have two specific questions about the behaviour of such issues in Java, assuming the above is correct:

  1. If a String can overflow, what happens when it does?
  2. What would the implications of this behaviour be?

Thanks in advance.

like image 662
Alan Lovell Avatar asked Dec 19 '25 07:12

Alan Lovell


1 Answers

To answer you first question, I had the luck of actually causing a error of such, and the execution just stopped throwing one of these errors:

java.lang.OutOfMemoryError: Requested array size exceeds VM limit

So that was my case, I don't know if that represents a security problem as buffer overflow in C and C++.

like image 93
Mihai Avatar answered Dec 20 '25 19:12

Mihai