TryBugHunt
javaInfinite loopMedium

Buffer sizing never finishes

BugFind the bug and fix the code

What it should do

growCapacity(needed) returns the smallest power of two that is at least needed (and at least 1), the way a growable buffer doubles its size, so growCapacity(5) returns 8.

What happens instead

growCapacity(5) never returns and the run times out.

public class Main {
    static int growCapacity(int needed) {
        int capacity = 0;
        while (capacity < needed) {
            capacity *= 2;
        }
        return capacity;
    }
}

Test a custom input to verify an edge case (e.g. empty lists, negative numbers, duplicates).

⏱️0:00
Hints
🏆 0 hints = Flawless Solve
Think & Test Cooldown
2:00 remaining

Take a moment to read the bug symptom and trace the code with Run & Check before unlocking Hint 1.

Hint 2
Unlocks after Hint 1
Hint 3
Unlocks after Hint 2

This bug belongs to the infinite loops pattern

The loop condition never becomes false, so the program runs until it is stopped.

What you'll practise

A medium Java debugging exercise about infinite loops: the loop condition never becomes false, so the program runs until it is stopped.

The checks your fix must pass

Signs of this kind of bug

Spoiler: why this bug happens(try it first; the hints get warmer one at a time)

Doubling only grows a number that is not zero. capacity starts at 0, and 0 * 2 is 0, so the loop condition 0 < 5 stays true forever. The loop does change capacity on every pass, which is why it looks fine at a glance, but a change that does not move towards the exit is no better than no change. With multiplication the starting value must be at least 1; with addition the step must be non-zero. When reviewing a loop, check both that the variable changes and that the change gets it closer to ending the loop, starting from its first value.

The pattern behind it: infinite loops.

More infinite loops to practise

Embed this challenge on your site

Paste this into any web page or blog post. Visitors fix the bug right there, in their browser.

<iframe src="https://trybughunt.com/embed/5d162cb1-1988-4e7b-b03b-bc93490921a0" title="Debugging challenge: Buffer sizing never finishes" width="100%" height="580" loading="lazy" style="border:1px solid #d4d4d8;border-radius:12px;max-width:760px"></iframe>
<p style="font-size:14px">Debugging challenge from <a href="https://trybughunt.com/challenges/5d162cb1-1988-4e7b-b03b-bc93490921a0">TryBugHunt</a></p>