TryBugHunt
cppLogic errorMedium

std::map operator[] creates unintended entries

BugFind the bug and fix the code

What it should do

Check if key exists in map and return final map size. Example: checkKeyCount("missing") -> 2

What happens instead

Map size increases from 2 to 3 after key presence check

#include <iostream>
#include <string>
#include <map>

int checkKeyCount(std::string searchKey) {
    std::map<std::string, int> cache;
    cache["alpha"] = 1;
    cache["beta"] = 2;

    // operator[] inserts default-initialized entry if key does not exist
    if (cache[searchKey] > 0) {
        // found
    }
    return cache.size();
}

int main() {
    std::cout << checkKeyCount("missing") << std::endl;
    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: In C++, std::map::operator[] automatically inserts a default-constructed value for missing keys. Checking cache[searchKey] created an unwanted {"missing", 0} entry, inflating the map size.

The fix: Use cache.find(searchKey) != cache.end() or cache.contains() (C++20) to check presence without mutation.

Remember: Never use std::map::operator[] to test if a key exists; use find() or contains().

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/afcb06a8-7a1a-4489-b264-116689e49bb7" title="Debugging challenge: std::map operator[] creates unintended entries" 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/afcb06a8-7a1a-4489-b264-116689e49bb7">TryBugHunt</a></p>