TryBugHunt
cppNull / UndefinedMedium

Score report lists students who are not in the class

BugFind the bug and fix the code

What it should do

pickScores(names, scores, wanted) returns the scores of the wanted students. Names that are not in the class are left out. Example: pickScores({"ana", "ben"}, {90, 75}, {"ben", "zoe"}) → {"ben": 75}

What happens instead

pickScores({"ana", "ben"}, {90, 75}, {"ben", "zoe"}) returns {"ben": 75, "zoe": 0}.

#include <map>
#include <string>
#include <vector>

std::map<std::string, int> pickScores(std::vector<std::string> names, std::vector<int> scores, std::vector<std::string> wanted) {
    std::map<std::string, int> all, out;
    for (size_t i = 0; i < names.size(); i++) all[names[i]] = scores[i];
    for (const std::string& w : wanted) {
        out[w] = all[w];
    }
    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 medium 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: all[w] with operator[] never fails. When w is not in the map it inserts w with the value 0 and returns that 0, so every unknown name appears in the result with a score of 0.

The fix: Check that the name exists first: if (all.count(w)) out[w] = all[w];

Remember: operator[] on a std::map is a write, even when you only meant to read. Use count, find or at when a missing key should mean "not there" instead of 0.

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/e64857f2-bb5a-42eb-80c5-4d75bb1bdc86" title="Debugging challenge: Score report lists students who are not in the class" 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/e64857f2-bb5a-42eb-80c5-4d75bb1bdc86">TryBugHunt</a></p>