bhylu.com

Advertisements

C++ Debugging

Expose the total and divisor of a calculation and use a debugger to test an assumption.

How it works

Start debugging with a small reproducible mismatch. Identify the first value that differs from the requirement and inspect the state just before it is computed. Compile with debug information and an appropriate low-optimisation setting for stepping. Breakpoints and watches reveal execution, but a plausible value observed once cannot make undefined behaviour valid. Sanitizers can detect many lifetime and bounds errors on supported toolchains; their availability and coverage need honest reporting rather than a claim that all builds are memory-safe.

Run it locally

Use a C++20 compiler and matching standard library in a separate lab folder. The command uses c++; substitute g++, clang++ or zig c++ for your toolchain. C++ does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed.

c++ -std=c++20 -Wall -Wextra -Wpedantic -Werror debugging.cpp -o lesson

On Windows use -o lesson.exe and run .\lesson.exe in PowerShell. On Unix-like systems run ./lesson. Thread examples may need -pthread on your platform.

Download the complete C++ source. Run file labs in a private empty directory, away from existing reports.

Example

C++20 · debugging.cpp

#include <iostream>
#include <vector>
#include <numeric>
#include <iomanip>

int main() {
    std::vector<int> minutes{10, 11, 12};
    long long total = std::accumulate(minutes.begin(), minutes.end(), 0LL);
    if (minutes.empty()) { return 1; }
    double mean = static_cast<double>(total) / static_cast<double>(minutes.size());
    std::cout << std::fixed << std::setprecision(2) << "total=" << total << " count=" << minutes.size() << " mean=" << mean << '\n';
}

Expected result

total=33 count=3 mean=11.00

The trace separates a wrong accumulated value from a wrong divisor or integer-division mistake. A breakpoint after accumulation should show thirty-three and three elements. For an input-dependent bug, save the smallest safe failing fixture. Keep debugging output distinct from the final report format so accidental diagnostics do not corrupt machine-readable output.

Consult the WG21 C++ working group and the C++ Core Guidelines for language references and design guidance. Check the selected standard version and your implementation’s library support.