True mastery in C++ comes from finding and eliminating subtle bugs. Below are five real-world debugging challenges frequently tested in industry technical screenings.
// SPOT THE BUG:
void processData() {
int* buffer = new int[500];
if (someCondition()) {
return; // BUG: Memory leak! buffer is NEVER freed if someCondition() is true!
}
delete[] buffer;
}
// THE MODERN C++ FIX (RAII):
void processDataFixed() {
std::vector<int> buffer(500); // 100% leak-proof even on early return!
if (someCondition()) {
return;
}
}
// SPOT THE BUG:
std::vector<int> v = {1, 2, 3, 4, 5};
for (auto it = v.begin(); it != v.end(); ++it) {
if (*it == 3) {
v.erase(it); // BUG: erase() invalidates 'it'! ++it in loop causes Undefined Behavior!
}
}
// THE MODERN C++ FIX:
// 1. Assign return value of erase(): it = v.erase(it);
// 2. OR modern C++20 erase algorithm:
std::erase(v, 3); // Clean, elegant, and zero bugs!
Boost your C++ proficiency by studying these closely connected core modules:
Solved standard lab programs.
Theoretical and architectural questions.
Comprehensive quick reference guide.