Undefined behaviour: Java and C++
Undefined behaviour is the C++ name for a program whose result the standard does not describe: the compiler may do anything, and a program that reads past an array, dereferences a null or overflows a signed integer is not a program with a wrong answer but a program outside the contract. Java has no such category. Each of those mistakes has a defined result, and most of them are exceptions.
The task
Four mistakes in one program: an index one past the end, a method call on a null, an addition that overflows a signed integer, and a division by zero. The Java program catches the three that throw and prints the fourth, and the same four lines in C++ are four undefined operations.
The Java version
public class Bounds {
public static void main(String[] args) {
int[] values = {1, 2, 3};
System.out.println("length: " + values.length);
System.out.println("index 2: " + values[2]);
try {
System.out.println(values[3]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("bounds: " + e.getMessage());
}
String missing = null;
try {
System.out.println(missing.length());
} catch (NullPointerException e) {
System.out.println("null: " + e.getClass().getSimpleName());
}
int max = Integer.MAX_VALUE;
System.out.println("overflow: " + (max + 1));
try {
System.out.println(1 / 0);
} catch (ArithmeticException e) {
System.out.println("zero: " + e.getMessage());
}
}
}
The compiler already knows about the last one and says so while it compiles. That warning is part of the output of the build:
javac -Xlint:all -d out Bounds.java
java -cp out Bounds
Bounds.java:24: warning: [divzero] division by zero
System.out.println(1 / 0);
^
1 warning
length: 3
index 2: 3
bounds: Index 3 out of bounds for length 3
null: NullPointerException
overflow: -2147483648
zero: / by zero
The checks Java makes
Every array access is checked against the length, which is why the fourth line is an ArrayIndexOutOfBoundsException with the index and the length in the message. Every method call on a reference checks for null, which is the fifth line. A division by zero on integers throws an ArithmeticException; the floating-point division gives an infinity instead, as IEEE 754 says.
The overflow is the one that does not throw. Java defines integer arithmetic modulo two to the thirty-two, so the maximum plus one is the minimum, and a program that needs to know uses Math.addExact, which throws an ArithmeticException instead of wrapping. The defined result is the opposite of undefined behaviour: a program can rely on it, test it and detect it.
The price is a check at every array access and every call, which the JIT removes where it can prove the check redundant. A Java program pays for safety in the interpreter and less in compiled code, and the guarantee holds everywhere, which is the trade the language made.
The C++ version
The same four operations, written the way a C++ program writes them. The block is not compiled here, because the image has no g++; not one of its lines has a defined result, and that is the subject.
#include <cstdio>
#include <climits>
#include <string>
int main() {
int values[3] = {1, 2, 3};
std::printf("index 2: %d\n", values[2]);
std::printf("index 3: %d\n", values[3]);
std::string* missing = nullptr;
std::printf("length: %zu\n", missing->size());
int max = INT_MAX;
std::printf("overflow: %d\n", max + 1);
int zero = 0;
std::printf("zero: %d\n", 1 / zero);
}
Each of the four is undefined behaviour. The read of values[3] may return a number, a crash or anything; the null dereference is a crash on most machines and is not required to be one; the signed overflow lets the optimiser assume the program never reaches it, which is why a loop that counts to INT_MAX can be optimised into an infinite loop; and the division by zero is undefined even though the hardware traps.
A compiler can warn about some of them, and the sanitizers can catch many at run time: -fsanitize=address,undefined instruments the program and reports the access before it happens. That is a diagnostic and not a definition: a program that is correct only under a sanitizer is still a program whose behaviour the standard does not describe.
What differs and why
The C++ choice is speed and reach: a bounds check on every access is a cost the language refuses to impose, and a program that has proved the index is in range should not pay for the proof twice. The standard says the programmer is responsible, and the optimiser is allowed to assume the responsibility was met. That is why std::vector has both operator[], unchecked, and at, which throws.
The Java choice is a guarantee: a program cannot read past an array, call a null or divide an integer by zero without an exception, and the exception is part of the API. A Java programmer can still be wrong, but the wrongness is a defined failure at a known line rather than a value that changes with the optimiser. The cost is the check, and the JIT is good at removing it where the proof is local.
The two languages agree on what a program should do and disagree on who pays. Java pays at every access and gives every program the guarantee; C++ pays nothing and gives the guarantee only to the programs that earned it. A C++ program that wants the Java guarantee uses at, std::span with a checked accessor or a sanitizer in its tests, and a Java program that wants the C++ speed uses an int loop the JIT can prove, which is the same proof on the other side.
The habit that breaks
The habit is to test a C++ program on one machine and conclude that its behaviour is defined. An out-of-bounds read that returns zero in a debug build may return a neighbouring field after inlining, and the test that passed is a test of one compilation. The same code in Java throws at the same line in every build, which is why a Java programmer can trust a stack trace and a C++ programmer needs a sanitizer and a second compiler.
The second habit is to translate the C++ reliance on wraparound into Java. Unsigned arithmetic does not exist in Java; a byte is signed; a hash written with << and + overflows silently and is defined, but a hash written with a division of a negative number is not the same value. The defined result is still a result a program must know, and the course's array algorithms lesson shows the checks on the Java side.
Where the group ends
This is the last page of the set. The hub lists the eight comparisons, from memory to this one, and each links the Java lesson and the C++ lesson it belongs to. The C++ lesson for this ground is pointers, and the Java lesson is array algorithms.
The Java program was compiled with OpenJDK 21.0.13 (javac) and run on Alpine Linux in a Docker container. The C++ program is shown and was not compiled here: the image has no g++.
Article author: Arthur Isaev