TryBugHunt
cppNull / UndefinedHard

Settings line with a bare flag crashes the parser

BugFind the bug and fix the code

What it should do

parseSettings(text) reads settings like "volume=7;size=12" into a map. Parts without an = are skipped. Example: parseSettings("volume=7;dark;size=12") → {"size": 12, "volume": 7}

What happens instead

parseSettings("volume=7;dark;size=12") crashes with: terminate called after throwing an instance of 'std::invalid_argument' what(): stoi

#include <map>
#include <sstream>
#include <string>

std::map<std::string, int> parseSettings(std::string text) {
    std::map<std::string, int> out;
    std::istringstream in(text);
    std::string part;
    while (std::getline(in, part, ';')) {
        size_t eq = part.find('=');
        out[part.substr(0, eq)] = std::stoi(part.substr(eq + 1));
    }
    return out;
}

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 null and undefined errors pattern

A null or dangling pointer dereferenced as if it pointed at a live object.

What you'll practise

A hard C++ debugging exercise about null and undefined errors: a null or dangling pointer dereferenced as if it pointed at a live object.

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: For "dark" there is no =, so find returns npos. npos + 1 wraps around to 0, part.substr(0) is the whole word "dark", and std::stoi("dark") throws std::invalid_argument.

The fix: Skip parts that have no =: if (eq == std::string::npos) continue;

Remember: The crash shows up in stoi, but the cause is two steps earlier, in a find result nobody checked. When parsing, check each separator was found before you cut the string around it.

The pattern behind it: null and undefined errors.

More null and undefined 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/690e9ef5-93cb-42ba-b5ff-f7ca82f9a4ea" title="Debugging challenge: Settings line with a bare flag crashes the parser" 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/690e9ef5-93cb-42ba-b5ff-f7ca82f9a4ea">TryBugHunt</a></p>