1. Goals
Reduce a failure to concrete data and reproducible steps.
Use warnings, breakpoints, and variable values to find its cause.
Check bounds, lifetimes, and arithmetic using several complementary checks.
2. Prerequisites
You know loops, indices, vector, references, lifetimes, RAII, exceptions,
and compilation. This lesson uses GDB as its debugger example; equivalent
operations are available in IDEs.
3. Explanation
Start with a specific expectation: the sum of {2, 4, 6} should be 12,
and an empty list should give 0. When something fails, retain the
smallest input that reproduces it, the build command, and the run steps.
Change one suspected cause at a time, using observations; then rerun the
failing case and boundary cases.
Here is an off-by-one reproduction. In a separate copy of main, keep
the includes and run this snippet. It accesses indices 0, 1, and 2
successfully, then throws std::out_of_range at index 3. If uncaught,
the exception terminates the program and buffered output may not all
appear. This is a checked exception, not an experiment with reading
invalid memory:
std::vector<int> sample{2, 4, 6};
for (std::size_t index = 0; index <= sample.size(); ++index) {
std::cout << sample.at(index) << '\n';
}The correct condition is index < sample.size(): the last index is
size() - 1 for a nonempty list. For an empty list, the correct loop
runs zero times. Replacing at with operator[] in the broken version
would make the invalid access undefined behavior; do not run that
version to guess its result.
Build with -Wall -Wextra -Wpedantic and read the first error first.
You can add -Werror to require warning fixes, as the Foundation
examples do. Warnings do not prove correctness: the <= condition
above can compile without a warning. Run the executable from the
latest successful build.
A breakpoint pauses execution where you want to observe it. In the full
example, sumStock receives stock, tracks index and total, and
calls stockAt. print index reads a variable in the current scope;
backtrace shows the call chain that reached this point. See GDB's
variable guide
and backtrace guide.
next advances a source line, generally stepping over calls; step
can enter functions with debug information. Use next for familiar
work and step for a call you need to inspect. continue resumes
until another stop or termination. See GDB's
stepping guide.
The corrected example uses index < stock.size() and at. sumStock
also rejects negative quantities and checks quantity > max - total
before adding, preventing signed int overflow. total stays
nonnegative and within max, making that subtraction valid.
stockAt returns a value, not a borrowed reference.
Before push_back, the program copies stock.front() into an independent
int. If it retained a const int& or pointer to the old element,
reallocation during vector growth could invalidate it. Depending on your
needs, copy the value or reacquire an element after mutation using a
still-valid index. An index does not preserve element identity across
insertion, erasure, or sorting.
AddressSanitizer (ASan) helps detect memory-access errors such as using freed storage. UndefinedBehaviorSanitizer (UBSan) checks some undefined behavior, including signed integer overflow. They observe runs with test inputs; they do not prove every possible path correct. ASan, UBSan.
Do not depend on a sanitizer to catch every invalid vector index,
especially an access beyond size() but within allocated capacity.
at checks against the element count. RAII manages resource release;
it does not replace bounds checks or correct summation logic.
4. Runnable example
This is the corrected version and does not execute invalid memory
accesses. It deliberately tries at(size()) and catches the specific
exception without printing an implementation-dependent error message.
#include <cstddef>
#include <iostream>
#include <limits>
#include <stdexcept>
#include <vector>
int stockAt(const std::vector<int>& stock, std::size_t index) {
return stock.at(index);
}
int sumStock(const std::vector<int>& stock) {
int total = 0;
for (std::size_t index = 0; index < stock.size(); ++index) {
const int quantity = stockAt(stock, index);
if (quantity < 0) {
throw std::invalid_argument("negative stock");
}
if (quantity > std::numeric_limits<int>::max() - total) {
throw std::overflow_error("stock total too large");
}
total += quantity;
}
return total;
}
int main() {
std::vector<int> stock{2, 4, 6};
const int total = sumStock(stock);
std::cout << "Total: " << total << '\n';
std::cout << "Empty total: " << sumStock({}) << '\n';
try {
const int missing = stockAt(stock, stock.size());
std::cout << "Unexpected value: " << missing << '\n';
} catch (const std::out_of_range&) {
std::cout << "Invalid index rejected\n";
}
const int snapshot = stock.front();
stock.push_back(8);
std::cout << "First value snapshot: " << snapshot << '\n';
std::cout << "Total after growth: " << sumStock(stock) << '\n';
return 0;
}Output:
Total: 12
Empty total: 0
Invalid index rejected
First value snapshot: 2
Total after growth: 20Build with debug line information and optimization disabled for easier inspection:
g++ -std=c++17 -Wall -Wextra -Wpedantic -Werror -g -O0 main.cpp -o stock-debug
gdb ./stock-debugTry the following GDB commands. After entering sumStock, two next
commands normally reach the declaration of quantity. If your displayed
location differs, use list and next to reach that line after total
and index have been initialized. Both are then 0; step at the
stockAt call enters that function.
break sumStock
run
next
next
print index
print total
step
backtrace
continueThe backtrace inside stockAt shows its callers, sumStock and main;
line numbers and addresses depend on your build. continue may stop at
sumStock again because main calls it several times. Use quit to
leave the debugger.
On Linux with a sanitizer-enabled Clang or GCC toolchain, additionally
check the corrected program as follows (replace clang++ with g++
for GCC):
clang++ -std=c++17 -Wall -Wextra -Wpedantic -g -O1 -fno-omit-frame-pointer -fsanitize=address,undefined main.cpp -o stock-sanitized
./stock-sanitized-g preserves debug information; -O1 enables light optimization, and
retaining frame pointers helps readable stack traces. Availability depends
on the toolchain and accompanying
runtime; Windows/MSYS2 GCC may not support this command. In PowerShell,
name the executable with .exe and run .\filename.exe. You can still
complete the exercises with warnings, a debugger, and at when
sanitizers are unavailable.
5. Common mistakes
Changing several things at once and losing track of which fixed the cause.
Using
<= size()or accessingfront()on an empty vector.Examining a variable before initialization or after leaving its scope.
Debugging an optimized build and mistaking optimized-away variables for lost data.
Retaining a reference across an operation that reallocates the vector.
Treating one warning-free or sanitizer-clean run as proof of correctness.
Catching every exception and silently continuing with a partial total.
6. Practice
Reproduce the
<=loop usingatin a separate copy. Record the first rejected index, fix the condition to<, and test an empty vector.In the corrected version, pause in
sumStockand observetotalbecoming2,6, then12. EnterstockAtonce to inspect the backtrace, then usenextfor later calls.Check
sumStock({})is0andsumStock({0, 5})is5.sumStock({-1})must throwinvalid_argument; summing{std::numeric_limits<int>::max(), 1}must throwoverflow_error. Catch the specific expected exception in your test instead of ignoring errors.Explain why
snapshotremains usable afterpush_back. Write a version that reacquiresstock.at(0)after appending; do not try dereferencing a possibly dangling old reference. If a sanitizer is available, also run valid and rejected inputs through the corrected program.
7. Self-check
Why can
<= size()compile cleanly and still be wrong? Answer: valid syntax and types do not prove correct bounds. Whenindex == size(), no such element exists;atthrows.When should you use
stepinstead ofnext? Answer: when you want to enter a called function and inspect it, with suitable debug information.nextnormally executes the call before stopping on another line in the current function.Why test boundary inputs when the sanitizer reports nothing? Answer: it observes only executed paths and certain error types. Logic mistakes, untested inputs, or some invalid container accesses can remain; contracts, bounds checks, and tests are still needed.
Sample code
Source file
cpp98_foundation/25_debugging_memory/main.cpp
#include <cstddef>
#include <iostream>
#include <limits>
#include <stdexcept>
#include <vector>
int stockAt(const std::vector<int>& stock, std::size_t index) {
return stock.at(index);
}
int sumStock(const std::vector<int>& stock) {
int total = 0;
for (std::size_t index = 0; index < stock.size(); ++index) {
const int quantity = stockAt(stock, index);
if (quantity < 0) {
throw std::invalid_argument("negative stock");
}
if (quantity > std::numeric_limits<int>::max() - total) {
throw std::overflow_error("stock total too large");
}
total += quantity;
}
return total;
}
int main() {
std::vector<int> stock{2, 4, 6};
const int total = sumStock(stock);
std::cout << "Total: " << total << '\n';
std::cout << "Empty total: " << sumStock({}) << '\n';
try {
const int missing = stockAt(stock, stock.size());
std::cout << "Unexpected value: " << missing << '\n';
} catch (const std::out_of_range&) {
std::cout << "Invalid index rejected\n";
}
const int snapshot = stock.front();
stock.push_back(8);
std::cout << "First value snapshot: " << snapshot << '\n';
std::cout << "Total after growth: " << sumStock(stock) << '\n';
return 0;
}