TryBugHunt
cppLogic errorMedium

Iterator invalidation in vector erase loop

BugFind the bug and fix the code

What it should do

Remove all even numbers from a vector of integers. Example: filterEvenNumbers([1, 2, 3, 4]) -> [1, 3]

What happens instead

Segmentation fault or skipped elements during vector iteration after erase

#include <iostream>
#include <vector>

std::vector<int> filterEvenNumbers(std::vector<int> nums) {
    for (auto it = nums.begin(); it != nums.end(); ++it) {
        if (*it % 2 == 0) {
            // erase invalidates it; incrementing ++it in loop causes UB
            nums.erase(it);
        }
    }
    return nums;
}

int main() {
    std::vector<int> res = filterEvenNumbers({1, 2, 3, 4});
    return 0;
}

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 logic errors pattern

The wrong operator, an inverted condition, a formula the right way round but backwards.

What you'll practise

A medium C++ debugging exercise about logic errors: the wrong operator, an inverted condition, a formula the right way round but backwards.

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)

What went wrong: Calling nums.erase(it) invalidates the iterator it and all subsequent iterators. Incrementing an invalidated iterator in the for-loop condition (++it) invokes undefined behavior and skips adjacent elements.

The fix: Assign the return value of erase to the iterator: it = nums.erase(it), and only increment ++it when no element was erased.

Remember: std::vector::erase returns the iterator following the removed element. Always capture its return value during loop erasure.

The pattern behind it: logic errors.

More logic errors 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/36c94d48-bfdf-40e3-aa88-36f73f446c01" title="Debugging challenge: Iterator invalidation in vector erase loop" 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/36c94d48-bfdf-40e3-aa88-36f73f446c01">TryBugHunt</a></p>