A file bigger than two gigabytes
A medium Java puzzle in the numeric overflow and precision family. One line below contains a real bug. Try to spot it first, then read why it fails and how to fix it.
Highlighted: line 6. Play this one as a puzzle without the answer.
What is wrong
File.length returns a long. Casting a value above 2,147,483,647 to int silently keeps only the low 32 bits, which can be negative or small, so the buffer is the wrong size or the allocation fails with NegativeArraySizeException.
The fix
How to avoid it next time
Narrowing casts never check the range. Use Math.toIntExact, which throws instead of wrapping, and avoid loading huge files whole.
Want the background? Read Files and I/O in the Java concepts library.
About numeric overflow and precision
Java integers wrap around silently when they exceed their range, with no exception. int and long arithmetic, integer division and implicit narrowing casts all produce wrong numbers that look plausible.
In code review: Look at the type of every operand, not the type of the variable receiving the result. Multiplication of two ints happens in int even when assigned to a long. Use Math.addExact, long literals and BigDecimal for money.
More puzzles in this family
Frequently asked questions
What is the bug in "A file bigger than two gigabytes"?
File.length returns a long. Casting a value above 2,147,483,647 to int silently keeps only the low 32 bits, which can be negative or small, so the buffer is the wrong size or the allocation fails with NegativeArraySizeException. The faulty line is line 6: int size = (int) f.length();
How do I fix it?
Replace it with: long size = f.length(); // stream the file in chunks instead of one array. Narrowing casts never check the range. Use Math.toIntExact, which throws instead of wrapping, and avoid loading huge files whole.
How do I catch numeric overflow and precision in code review?
Look at the type of every operand, not the type of the variable receiving the result. Multiplication of two ints happens in int even when assigned to a long. Use Math.addExact, long literals and BigDecimal for money.
Is there a new puzzle every day?
Yes. The daily Spot the Bug puzzle picks one of these snippets for each UTC day, with the difficulty set by the weekday. Your streak is stored only in your browser.