Site Guide

Find your way around the Engineering Club.

Know what you need? Search for a component, concept or project.

Around the site

Start

Labs

TestingExperimental

Build

Club

LearnExperimental

Go a little deeper

Entry points to larger collections. Use Search for individual records.

Learning paths & reference

Inside PiCrawlerExperimental

Inside Inventory

← C++ Worked Programs

Learn / Debugging autopsy

Bounds Autopsy: Size Is the Contract

From a confirmed heap overflow to checked access

BeginnerDesktop C++17 · runnable source

What you will learn

The complete source

main.cpp

main.cpp
#include <iostream>
#include <stdexcept>
#include <vector>

int main() {
    std::vector<int> values{100, 200, 50, 75};
    std::cout << "Size: " << values.size() << '\n';
    try {
        values.at(10) = 100;
    } catch (const std::out_of_range&) {
        std::cout << "Index 10 rejected; valid indices are 0 through 3.\n";
    }
    values.push_back(100);
    std::cout << "After append: size " << values.size()
              << ", last " << values.back() << '\n';
}
Source integrity

SHA-256 b36bfda26b2038b1f2be56b0f05ebb059417f3f50ce85210da0bb41d22133287. Display, copy and approved download use the same source.

What it does and why it was selected

The archived vector experiment compiles yet writes index 10 in a vector with only four elements. The array experiment combines uninitialized reads with accesses outside a ten-element object. These are powerful debugging examples because they demonstrate why a normal-looking run or successful compile cannot prove memory safety.

Actual execution

The canonical corrected program creates a vector of four initialized integers and prints its size. at(10) checks the requested index and throws out_of_range before assignment can occur. The catch prints a stable explanation rather than a platform-specific exception message. push_back then appends a fifth actual element; size becomes 5 and back returns the new value 100. The demonstration intentionally attempts an invalid checked operation and catches it. It performs no out-of-bounds unchecked read or write.

Mathematical or state model

A vector with size 4 has valid element indices 0,1,2,3. Capacity can exceed size but does not create elements in the unused allocation. operator[] assumes the index is valid; it neither appends nor guarantees an exception. at checks against size. push_back creates one new element and increases size. For a built-in array of length 10, valid indices are 0..9, and no dynamic resizing operation exists.

Design and C++ mechanics

The broken historical snippets are stored as explicitly labeled text excerpts, separate from canonical runnable source. The verification record contains the actual sanitizer failure from the freshly compiled original t_vectors.cpp. Its invalid write triggered AddressSanitizer heap-buffer-overflow. The t_arrays.cpp execution stopped on an out-of-range index; its earlier uninitialized reads are also defects, but ordinary AddressSanitizer is not a general detector of uninitialized scalar values. A sanitizer’s first report is not an exhaustive inventory of every source defect.

Historical differences and limits

Changing operator[] to at makes an invalid request observable; it does not explain whether the program intended append, resize or access to an existing element. Those choices have different behavior. reserve(11) would allocate room without increasing size and would not make index 10 a valid vector element. resize(11) would create elements, but doing that blindly would conceal an incorrect assumption if the application was only supposed to contain four values.

Useful extensions

Create a separate bounded indexing exercise where a user selects an index and the program validates it before operator[]. Compare that explicit domain check with at’s exception. If introducing iterators, demonstrate how insertion or reallocation can invalidate them; do not infer iterator stability merely from safe element access in this small example.

Source-linked explanations

Follow each line reference to its marked source region. The explanations below are bound to the reviewed source hash and preserve the supplied teaching layers.

Size defines valid existing elements

main.cpp, lines 6–7 →

Initializer-list construction creates four actual elements.

Technical explanation
Initializer-list construction creates four actual elements. values.size reports four, so indices 0..3 are valid. Capacity is a separate allocation property and is deliberately not used as a validity condition.
Syntax
Capacity is a separate allocation property and is deliberately not used as a validity condition.
Effect on the program
Capacity is a separate allocation property and is deliberately not used as a validity condition.
Common mistake
Calling index 10 the tenth element also ignores zero-based indexing; it is outside this four-element vector either way.

vectorsindices

Checked failure avoids undefined behavior

main.cpp, lines 8–12 →

values.at(10) compares the index with size and throws before assignment to a nonexistent element.

Technical explanation
values.at(10) compares the index with size and throws before assignment to a nonexistent element. Catching out_of_range handles that specific failure. The diagnostic deliberately does not quote library what() text, keeping the example transcript stable across implementations.
Syntax
The diagnostic deliberately does not quote library what() text, keeping the example transcript stable across implementations.
Effect on the program
The diagnostic deliberately does not quote library what() text, keeping the example transcript stable across implementations.
Common mistake
The archived operator[] write is not made safe by try/catch, because it need not throw at all.

exceptionsundefined behavior

Appending creates a new element

main.cpp, lines 13–16 →

push_back changes size from 4 to 5 and constructs value 100 at the new final index 4.

Technical explanation
push_back changes size from 4 to 5 and constructs value 100 at the new final index 4. back is safe because the vector is now known to be nonempty. Allocation may change, but this source retains no iterators or element references across append.
Syntax
Allocation may change, but this source retains no iterators or element references across append.
Effect on the program
Allocation may change, but this source retains no iterators or element references across append.
Common mistake
reserve can change capacity without creating elements. It is not a replacement for push_back or resize.

vectorsmemory lifetime

Recorded input and output

Captured from the compiled canonical program in the supplied verification package. These are recorded terminal sessions, not an interactive browser runner.

Sample run

Arguments
None
Recorded exit status
0

Program input

No standard input.

Program output

Size: 4
Index 10 rejected; valid indices are 0 through 3.
After append: size 5, last 100

Build and run

From this folder, with a configured C++17 compiler:

sh
g++ -std=c++17 -Wall -Wextra -Wpedantic main.cpp -o program
./program

On Windows GCC, build with -o program.exe and use .\program.exe. These are desktop examples; VS Code is an editor, the compiler builds an executable, and the terminal runs it.

Windows run command from the supplied metadata: .\program.exe.

Desktop compiler setup and platform limits. How headers and translation units fit together.

Supporting material

Historical vector defect — explanatory excerpt, do not execute

Broken historical excerpt for diagnosis. Study the corrected runnable source above; this excerpt is not an execution exercise.

vector-bounds-broken.cpp.txt
// HISTORICAL BROKEN EXCERPT. Do not compile as a worked program.
// From t_vectors.cpp, original lines 20-27. Submission metadata omitted.
vector<int> v2 = {100, 200, 50, 75};
v2[10] = 100; // OUT OF BOUNDS: size is 4; operator[] does not append.
Source integrity

SHA-256 00e4b89be7cd299d181232e731dbb089a99a835d9ddc58f024090dca72bdb124. Display, copy and approved download use the same source.

Historical array defect — explanatory excerpt, do not execute

Broken historical excerpt for diagnosis. Study the corrected runnable source above; this excerpt is not an execution exercise.

array-bounds-broken.cpp.txt
// HISTORICAL BROKEN EXCERPT. Not canonical runnable source.
// From t_arrays.cpp, original lines 40-54. Comments condensed.
int arr_2[10]; // Uninitialized elements.
for (int i = 0; i < 106; i++) {
    cout << arr_2[i]; // Uninitialized first 10 reads; then out of bounds.
}
for (int i = 0; i < 15; i++) {
    arr_2[i] = i * 2; // Indices 10..14 are outside the array.
}
Source integrity

SHA-256 fbf0051733b637d38ab25398b3e30e438bb84e116d917eb43879ae92d96c4c9e. Display, copy and approved download use the same source.

Verification and provenance

  • Source inspected
  • Compile verified
  • Warning reviewed
  • Behavior verified
  • Sanitizer checked

Supplied evidence: 1 recorded behavior/error cases and 1 address/undefined-behavior sanitizer cases for this exact source. These are tested cases, not an exhaustive correctness claim.

Recorded compiler: g++ (Ubuntu 13.3.0-6ubuntu2~24.04) 13.3.0.

LeakSanitizer: disabled because unavailable under runtime tracing. Windows/MSVC and macOS execution are not certified by this evidence.

Source origin and publication treatment

Corrected debugging example

User-supplied origin; no independent authorship or license determination. Instructor code is not included.

New or rewritten source, limited sanitized historical excerpts when useful

No new license is asserted by this publication.