Your country

Tools that support it use your country for local currency, number formats, units and paper size. Your choice is saved only in this browser.

Type a name or a two-letter code. Use the up and down arrow keys to move through the countries, Enter to choose one and Escape to close.

C++  Module 6 – References, pointers and memory

Object lifetime and undefined behaviour in C++

What undefined behaviour means in C++, how dangling references and overflows cause it, and why a build that works at -O0 can fail at -O2.

  • Intermediate
  • 35 minutes
  • Examples run with Clang 21.0.0, GCC 16.2.0 and Python 3.14.8
  • By MySmartCoPilot
Free lesson, Pro answers: 35 minutes
Free: the whole lesson. With a pass: the model answers to its 2 interview questions.

What you will learn

  • Distinguish undefined behaviour from unspecified and implementation-defined behaviour
  • Predict when an object's lifetime begins and ends, for each storage duration and for temporaries
  • Find and fix a reference that a growing vector has left dangling
  • Show why a program that works in one build proves nothing when it has undefined behaviour
  • Match the common causes of undefined behaviour with the checks that find them, C++26 hardening included

Before you start

What you’ll learn · Before you start

What you will learn

  • Distinguish undefined behaviour from unspecified and implementation-defined behaviour
  • Predict when an object's lifetime begins and ends, for each storage duration and for temporaries
  • Find and fix a reference that a growing vector has left dangling
  • Show why a program that works in one build proves nothing when it has undefined behaviour
  • Match the common causes of undefined behaviour with the checks that find them, C++26 hardening included

Before you start

On this page

Add 10 to a balance 5 below the largest int: one build of the same file rejects the deposit, and three others accept it and leave a balance of −2,147,483,644. No compiler is broken. The program has undefined behaviour: What a program does when it breaks a rule for which the C++ standard sets no requirements, such as reading past the end of an array. The compiler may assume it never happens, so the result can change with the compiler and the optimisation level., so the C++ standard sets no requirements at all for what it does: a crash, a wrong answer and a right-looking one are all allowed, and the result can change with the compiler, the optimisation level or the run.

Many of these bugs come from an object’s lifetime: The part of a run during which an object exists: it begins once memory of the right size and alignment is obtained and the object's initialisation is complete, and ends when its destructor starts or its memory is released or reused., which begins once the object has its memory and has been initialised and ends when its destructor starts or its memory is given back. A pointer or reference that outlives its object is dangling reference: A reference whose object has already been destroyed, such as one returned from a function to its own local variable. Reading or writing through it is undefined behaviour, even when the program happens to print the right value. More in “C++ references: lifetime extension and dangling”. Below you will watch lifetimes begin and end, see a vector leave a reference behind and read programs whose output changes between -O0 and -O2 on GCC 16 and Apple clang 21, then meet the two places where C++26 makes such bugs less dangerous.

Undefined behaviour removes every requirement on the run

The standard sorts the behaviour it does not pin down into three kinds:

Kind What the standard requires Example
implementation-defined behaviour: Behaviour that the C++ standard leaves to each implementation, which must document its choice, such as sizeof(int). A program that relies on it is valid, but may give other results with another compiler or platform. Each compiler picks a behaviour and documents it sizeof(int)
unspecified behaviour: Behaviour the standard allows in more than one way, without requiring the choice to be documented or kept the same, such as the order in which function arguments are evaluated. The program stays valid but must not depend on the choice. More in “Why i++ + ++i has no single answer in C++” The compiler picks one of the allowed behaviours and need not say which The order in which a function’s arguments are evaluated
Undefined No requirements at all Reading past the end of an array, overflowing an int, changing a const object

The first two are safe to live with: your program has a meaning, even if it varies between compilers. Undefined behaviour is different in two ways. It covers the whole run, not only the faulty line: the standard says that once an execution contains an undefined operation, nothing is required of it, “not even with regard to operations preceding” it. And nobody has to tell you. The compiler need not warn, the program need not crash, and the wrong result may only appear years later with another compiler.

Undefined behaviour matters because it is invisible to tests that happen to pass. The compiler is allowed to assume it never happens, so a bug can hide in a debug build and appear in the release build, or the other way round.

Why would a language allow this? Because checking costs time. C++ does not check every v[i] against the size or every a + b for overflow; it makes the bad cases undefined, so the fast code is the correct code for every valid program. Optimisers go one step further and use the rules as facts: if overflow cannot happen in a valid program, code that only makes sense after an overflow can be deleted.

There is one place where the compiler must catch undefined behaviour for you: a constant expression: An expression the compiler can evaluate while it compiles, such as 6 * 7 or a call of a constexpr function with constant arguments. Array sizes, template arguments, case labels and static_assert need one, and one may never contain undefined behaviour. More in “C++ const, constexpr, consteval and constinit”, which is evaluated while compiling. Here one_more is called at compile time with the largest int:

constexpr_ub.cpp C++ · constexpr_ub.cpp
#include <limits>

// The same overflow as in deposit.cpp, evaluated by the compiler instead of at run time.
constexpr int one_more(int x) { return x + 1; }

constexpr int fits = one_more(41);
constexpr int too_big = one_more(std::numeric_limits<int>::max());
Both compilers refuse the overflow at compile time Python · constexpr_session.py
from session import run

# A constant expression may not contain undefined behaviour, so both compilers refuse to compile this file.
run("""
clang++ -std=c++23 -c constexpr_ub.cpp -o constexpr_ub.o
g++-16 -std=c++23 -c constexpr_ub.cpp -o constexpr_ub.o
""")

Output

$ clang++ -std=c++23 -c constexpr_ub.cpp -o constexpr_ub.o
constexpr_ub.cpp:7:15: error: constexpr variable 'too_big' must be initialized by a constant expression
    7 | constexpr int too_big = one_more(std::numeric_limits<int>::max());
      |               ^         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
constexpr_ub.cpp:4:42: note: value 2147483648 is outside the range of representable values of type 'int'
    4 | constexpr int one_more(int x) { return x + 1; }
      |                                          ^
constexpr_ub.cpp:7:25: note: in call to 'one_more(2147483647)'
    7 | constexpr int too_big = one_more(std::numeric_limits<int>::max());
      |                         ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1 error generated.
[exit status 1]
$ g++-16 -std=c++23 -c constexpr_ub.cpp -o constexpr_ub.o
constexpr_ub.cpp:7:33:   in 'constexpr' expansion of 'one_more(std::numeric_limits<int>::max())'
    7 | constexpr int too_big = one_more(std::numeric_limits<int>::max());
      |                         ~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
constexpr_ub.cpp:4:42: error: overflow in constant expression [-fpermissive]
    4 | constexpr int one_more(int x) { return x + 1; }
      |                                        ~~^~~
[exit status 1]

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 constexpr_session.py

Apple clang names the value that does not fit, 2,147,483,648, and GCC calls it an overflow in a constant expression. The same function called while the program runs would compile without a word.

Key idea

Undefined behaviour is not an unknown result but no requirement at all, on the whole run, and the compiler may assume that it never happens.

Checkpoint

Check: Undefined, unspecified and implementation-defined

  1. Question 1 of 2 In f(a(), b()) the standard does not say whether a() or b() runs first, and the compiler need not tell you which it chose. What kind of behaviour is that?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: Unspecified

    The standard leaves three kinds of things open. Unspecified behaviour is one of several allowed outcomes, chosen without telling you; implementation-defined behaviour is chosen and documented; undefined behaviour has no requirements at all.

  2. Question 2 of 2 A program prints "start", then reads past the end of an array. What does the standard require of that run?

    Choose one answer.

    A hint

    The standard's wording covers more than the faulty line.

    Show the answer: Question 2 of 2

    Answer: Nothing at all, not even of the operations before the bad read

    Undefined behaviour covers the whole run. In practice "start" usually appears, but nothing in the standard promises it, and an optimiser may change code before the bad read because of what comes after it.

Each object’s lifetime starts and ends at a fixed point

Every object in a C++ program has a lifetime. The standard’s rule, in plain words: an object’s lifetime begins when memory of the right size and alignment has been obtained for it and its initialisation is complete; for a class type it ends when the destructor call starts, and for any object when its memory is released or reused. Where that memory comes from is the object’s storage duration: How long an object exists while a program runs: automatic (until the end of its block), static (the whole run), thread (the life of one thread) or dynamic (from new until delete). It belongs to the object, while scope belongs to its name. More in “Scope, storage duration, linkage and namespaces”:

  • Static: global variables and static ones, which live until the program ends.
  • Automatic: local variables, which end at the closing brace of their block, in reverse order of creation.
  • Dynamic: objects made with new, which end at the matching delete.
  • Thread: thread_local variables, one per thread, which end with their thread.

temporary object: An unnamed object made while an expression is evaluated, such as the std::string that city + ' Central' produces. It is destroyed at the end of the full expression that made it, unless a reference bound to it keeps it alive. More in “std::string and std::string_view”, such as a function’s return value that nobody stores, end at the end of the full-expression: An expression that is not part of a larger one, usually a whole statement or the initialiser of a declaration. The temporaries made while it is evaluated are destroyed at its end, unless lifetime extension keeps one alive. More in “C++ references: lifetime extension and dangling” that created them, unless a reference is bound directly to them. The type in tracer.h prints a line when an object’s lifetime begins and when it ends:

Watching lifetimes

lifetime.cpp

#include "tracer.h"

Tracer global{"global"};  // static storage: lives until the program ends

Tracer make(std::string name) { return Tracer{std::move(name)}; }

int main() {
    std::println("main starts");
    {
        Tracer local{"local"};  // automatic storage: lives until the closing brace
        std::println("  inside the block");
    }
    std::println("after the block");

    make("temporary");  // a temporary: lives until the end of this statement
    std::println("after the temporary");

    const Tracer& kept = make("bound to a reference");  // lives as long as the reference
    Tracer* heap = new Tracer{"dynamic"};               // dynamic storage: lives until delete
    delete heap;
    std::println("main ends, still holding {}", kept.name);
}

tracer.h

#pragma once
#include <print>
#include <string>
#include <utility>

// An object that says when its lifetime begins and when it ends.
struct Tracer {
    std::string name;

    explicit Tracer(std::string n) : name(std::move(n)) { std::println("  begin {}", name); }
    Tracer(Tracer&& other) noexcept : name(other.name + " (moved)") { std::println("  begin {}", name); }
    ~Tracer() { std::println("  end   {}", name); }
};
When each object begins and ends Python · lifetime_session.py
from session import run

# When each object's lifetime begins and ends, built with both compilers.
run("""
clang++ -std=c++23 -Wall -Wextra lifetime.cpp -o lifetime && ./lifetime
g++-16 -std=c++23 -Wall -Wextra lifetime.cpp -o lifetime-gcc && ./lifetime-gcc > gcc.txt && ./lifetime > clang.txt && cmp gcc.txt clang.txt && echo "GCC's build prints the same lines"
""")

Output

$ clang++ -std=c++23 -Wall -Wextra lifetime.cpp -o lifetime && ./lifetime
  begin global
main starts
  begin local
  inside the block
  end   local
after the block
  begin temporary
  end   temporary
after the temporary
  begin bound to a reference
  begin dynamic
  end   dynamic
main ends, still holding bound to a reference
  end   bound to a reference
  end   global
$ g++-16 -std=c++23 -Wall -Wextra lifetime.cpp -o lifetime-gcc && ./lifetime-gcc > gcc.txt && ./lifetime > clang.txt && cmp gcc.txt clang.txt && echo "GCC's build prints the same lines"
GCC's build prints the same lines

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 lifetime_session.py

Step through the same run: each box is one of the program’s objects, and each step is a line it printed.

Interactive · step by step Five objects of lifetime.cpp, from begin to end Step through the run. Each box is one object of lifetime.cpp, and each step is a line the program printed.
Five objects of lifetime.cpp, from begin to end, step 8 of 8. Showing global (ended after main), main (returned), local (ended at the brace), make("temporary") (began and ended on line 15), kept, a const Tracer& (ended with main), new Tracer{"dynamic"} (ended at delete). In focus: global.globalended after mainmainreturnedlocalended at the bracemake("temporary")began and ended on line 15kept, a const Tracer&ended with mainnew Tracer{"dynamic"}ended at delete

The drawing shows the whole scene; its 8 steps are listed below.

Every step as text
  1. Before main. The first line is begin global, printed before main starts. A global has static storage duration: its lifetime begins before main and lasts until the program ends.
  2. A block opens. main starts, and inside the block local begins. It has automatic storage duration, so its lifetime is tied to the block that declares it.
  3. The closing brace. At the closing brace of the block local ends, and end local prints before after the block. Automatic objects end at the end of their block, in reverse order of creation.
  4. One line long. make("temporary") returns an object that nobody stores. It begins and ends within the same statement: a temporary ends at the end of the full expression that created it, before after the temporary is printed.
  5. Bound to a reference. The next temporary is bound directly to const Tracer& kept, so it lives as long as the reference. begin bound to a reference prints, and no end follows yet.
  6. new, then delete. new Tracer{"dynamic"} begins an object with dynamic storage duration, and delete heap on the next line ends it: begin dynamic and end dynamic print one after the other.
  7. main ends. main prints main ends, still holding bound to a reference: the object kept refers to is still alive. At main's closing brace kept goes out of scope, and end bound to a reference prints.
  8. The last line. After main has returned, the global ends: end global is the last line. Every object was fine while it was alive; the bugs start when a pointer or reference outlives one of them.

The global begins before main and ends after it. The temporary ends on its own line, before “after the temporary” is printed, while the one bound to const Tracer& kept lives as long as the reference, until main ends. This is lifetime extension: The rule that a temporary bound directly to a const T& or a T&& lives as long as that reference. Passed through a function, as an argument or as a returned reference, the temporary still ends with its full-expression. More in “C++ references: lifetime extension and dangling”, and it works only for a reference bound directly to the temporary. Every object is fine while it is alive. The trouble starts when a pointer or a reference is still around after its object’s lifetime has ended.

Checkpoint

Check: When a lifetime begins and ends

  1. Question 1 of 2 make("temporary"); in lifetime.cpp stores its result nowhere. When does that object's lifetime end?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: At the end of that statement, before "after the temporary" is printed

    A temporary that no reference is bound to ends at the end of the full expression that created it. The program printed begin temporary and end temporary one after the other, before after the temporary.

  2. Question 2 of 2 const Tracer& kept = make("bound to a reference"); binds a reference to the object make returns. When does that object end?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: When kept goes out of scope at the end of main

    Lifetime extension keeps a temporary alive for as long as the reference bound directly to it. kept is a local of main, so its object ends at main's closing brace, after "main ends, still holding bound to a reference".

A vector that grows leaves its old references dangling

A std::vector keeps its elements in one array. When push_back needs more room than the array has, the vector makes a reallocation: What a std::vector does when an element must be added and its buffer is full: it allocates a larger buffer, moves the elements into it and frees the old one, so every pointer, reference and iterator to the elements dangles. More in “std::vector: the container to reach for first”: it allocates a bigger array, moves the elements across and frees the old one. The elements you had a reference to have ended. Watch it with Tracer elements and a capacity of 2:

relocate.cpp C++ · relocate.cpp
#include <vector>
#include "tracer.h"

int main() {
    std::vector<Tracer> queue;
    queue.reserve(2);
    queue.emplace_back("A");
    queue.emplace_back("B");
    std::println("size {}, capacity {}", queue.size(), queue.capacity());

    std::println("push C:");
    queue.emplace_back("C");  // no room left: a bigger array, then A and B move into it
    std::println("size {}, capacity {}", queue.size(), queue.capacity());
    std::println("main ends");
}
The old elements end when the vector grows Python · relocate_session.py
from session import run

# A vector that runs out of room: watch the old elements end. libc++ (Apple clang) first, then libstdc++ (GCC).
run("""
clang++ -std=c++23 -Wall -Wextra relocate.cpp -o relocate && ./relocate
g++-16 -std=c++23 -Wall -Wextra relocate.cpp -o relocate-gcc && ./relocate-gcc
""")

Output

$ clang++ -std=c++23 -Wall -Wextra relocate.cpp -o relocate && ./relocate
  begin A
  begin B
size 2, capacity 2
push C:
  begin C
  begin A (moved)
  begin B (moved)
  end   A
  end   B
size 3, capacity 4
main ends
  end   C
  end   B (moved)
  end   A (moved)
$ g++-16 -std=c++23 -Wall -Wextra relocate.cpp -o relocate-gcc && ./relocate-gcc
  begin A
  begin B
size 2, capacity 2
push C:
  begin C
  begin A (moved)
  end   A
  begin B (moved)
  end   B
size 3, capacity 4
main ends
  end   A (moved)
  end   B (moved)
  end   C

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 relocate_session.py

Both libraries build C in a new array with room for 4, move A and B across, and end the old A and B. They differ in small ways the standard leaves open, such as the order in which the elements are destroyed at the end of main. The diagram shows the same growth in the vector of the next program, three marks with no spare room, and what it does to a reference taken before the call:

A full vector moves its elements to a bigger array on push_back and frees the old one, while a reference still points at the old array.1. Before push_back(100)2. After the callint& firstarray A70 | 80 | 90markssize 3capacity 3int& firstarray A, freedno object herearray B70 | 80 | 90 | 1002 slots freemarkssize 4capacity 6refers to 70ownsstill refers hereownscopy into B, add 100, free A

Why a reference into a vector dangles after push_back

Text description of the diagram

The diagram has two panels, before and after the call marks.push_back(100).

Before the call, the vector marks has size 3 and capacity 3. It owns array A, which holds 70, 80 and 90. The reference first refers to the element 70 in array A.

The call needs room for a fourth element, so the vector allocates a bigger array B with capacity 6, copies or moves 70, 80 and 90 into it, adds 100, and frees array A.

After the call, marks has size 4 and owns array B. Array A is freed, and no object lives there any more, but first still refers to the place where 70 used to be. Reading first is now undefined behaviour.

Now the bug. first is taken from the array before push_back and read after it:

invalidate.cpp C++ · invalidate.cpp
#include <print>
#include <vector>

int main() {
    std::vector<int> marks{70, 80, 90};
    int& first = marks[0];  // refers to an element inside the vector's array
    std::println("first = {}, capacity {}", first, marks.capacity());

    marks.push_back(100);   // the array is full: the elements move to a bigger one
    std::println("capacity {}", marks.capacity());
    std::println("first = {}", first);  // reads the old array, which push_back freed
}
Three runs of a build without checks Python · invalidate_session.py
from session import run

# The reference that outlived its element, built without any checks and run three times.
run("""
clang++ -std=c++23 invalidate.cpp -o invalidate
./invalidate
./invalidate
./invalidate
""")

Output

$ clang++ -std=c++23 invalidate.cpp -o invalidate
$ ./invalidate
first = 70, capacity 3
capacity 6
first = 2
$ ./invalidate
first = 70, capacity 3
capacity 6
first = 2
$ ./invalidate
first = 70, capacity 3
capacity 6
first = 2

This output changes from run to run: The last line reads freed memory, which holds whatever the memory allocator wrote there, so the number can change from run to run and from machine to machine.

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 invalidate_session.py

No crash and no message: the program reads the freed array and prints a number that is not 70, one that can differ on another day. AddressSanitizer, a checking mode of both compilers that the sanitizers lesson covers in depth, turns the same mistake into a report:

The same program built with AddressSanitizer Python · invalidate_asan_session.py
from session import run

# The same program built with AddressSanitizer, by each compiler: the read on line 11 is stopped and explained.
run("""
clang++ -std=c++23 -g -fsanitize=address -fno-omit-frame-pointer invalidate.cpp -o invalidate
./invalidate
g++-16 -std=c++23 -g -fsanitize=address -fno-omit-frame-pointer invalidate.cpp -o invalidate-gcc
./invalidate-gcc
""")

Output

$ clang++ -std=c++23 -g -fsanitize=address -fno-omit-frame-pointer invalidate.cpp -o invalidate
$ ./invalidate
first = 70, capacity 3
capacity 6
==…==ERROR: AddressSanitizer: heap-use-after-free on address 0x…
READ of size 4 at 0x… thread T0
    #8 in main invalidate.cpp:11
0x… is located 0 bytes inside of 12-byte region [0x…,0x…)
freed by thread T0 here:
    #11 in main invalidate.cpp:9
previously allocated by thread T0 here:
    #10 in main invalidate.cpp:5
SUMMARY: AddressSanitizer: heap-use-after-free
[67 more lines of the report left out]
==…==ABORTING
[exit status 134]
$ g++-16 -std=c++23 -g -fsanitize=address -fno-omit-frame-pointer invalidate.cpp -o invalidate-gcc
$ ./invalidate-gcc
first = 70, capacity 3
capacity 6
==…==ERROR: AddressSanitizer: heap-use-after-free on address 0x…
READ of size 4 at 0x… thread T0
    #6 in main invalidate.cpp:11
0x… is located 0 bytes inside of 12-byte region [0x…,0x…)
freed by thread T0 here:
    #9 in main invalidate.cpp:9
previously allocated by thread T0 here:
    #7 in main invalidate.cpp:5
SUMMARY: AddressSanitizer: heap-use-after-free
[60 more lines of the report left out]
==…==ABORTING
[exit status 134]

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 invalidate_asan_session.py

Step through the program and the report together, with the arrays the vector owns on the right:

Interactive · step by step A reference that outlives its element Step through invalidate.cpp. The left column holds the names in main, the right column the arrays the vector owns.
A reference that outlives its element, step 7 of 7. Showing marks, the vector (size 4, capacity 6), Array A (heap-use-after-free), int& first (std::size_t first = 0), Array B (70 | 80 | 90 | 100). In focus: int& first, Array B.ownsmarks, the vectorsize 4, capacity 6Array Aheap-use-after-freeint& firststd::size_t first = 0Array B70 | 80 | 90 | 100

The drawing shows the whole scene; its 7 steps are listed below.

Every step as text
  1. Three marks. Line 5 builds marks from 70, 80 and 90. The vector allocates array A with room for exactly three ints: size 3, capacity 3.
  2. first = marks[0]. Line 6 binds the reference first to the element 70 inside array A, and line 7 prints first = 70, capacity 3. The element is alive and the reference is fine.
  3. No room for 100. Line 9 calls push_back(100). Array A is full, so the vector allocates array B with room for 6, copies 70, 80 and 90 into it and adds 100.
  4. A is freed. The vector frees array A and keeps only B; line 10 prints capacity 6. The element 70 that first referred to ended with array A, and nothing told first.
  5. The read on line 11. first still refers into the freed array. Reading it is undefined behaviour: the recorded build without checks printed first = 2 on all three runs, a number that is not 70 and need not be the same on another machine.
  6. What AddressSanitizer says. Built with AddressSanitizer, the same read stops the program with heap-use-after-free: a READ of size 4 on line 11, memory freed by the push_back on line 9 and allocated on line 5.
  7. The fix: an index. Keep a position instead of a reference, std::size_t first = 0, and write marks[first] when you need the element. It reads 70 from array B, whatever the vector has done with its arrays.

The report names the error (heap-use-after-free), the read on line 11, the push_back on line 9 that freed the memory, and line 5, where the vector first allocated it. The standard states the rule of iterator invalidation: What happens to the iterators, pointers and references into a container after an operation that moves or removes its elements, such as a push_back that reallocates or an erase: they no longer refer to valid elements, and using them is undefined behaviour.: when push_back reallocates, every reference, pointer and iterator to the elements becomes invalid. The fixes are about who holds on to what:

  • Keep an index (std::size_t first = 0;) and write marks[first] when you need the element.
  • Take the reference after the last insertion, not before.
  • Call reserve with the final size first, when you know it, so that no reallocation happens. This is fragile: one extra push_back brings the bug back.
  • Use a container whose references survive insertions, such as std::deque for insertions at either end, or std::list.

Key idea

A reference, pointer or iterator into a vector is only as good as the array behind it: keep an index, or take the reference after the last insertion.

Checkpoint

Check: References into a growing vector

  1. Question 1 of 2 In invalidate.cpp, what does first refer to after marks.push_back(100)?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: The place in the freed array where 70 used to be

    With size 3 and capacity 3 there was no spare slot, so push_back reallocated: a new array with room for 6, the elements copied across, the old array freed. first dangles, and the build without checks read 2 instead of 70.

  2. Question 2 of 2 To keep first valid, a colleague calls marks.reserve(4) before taking the reference. Why does the lesson call that fix fragile?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: One more push_back than planned reallocates again and brings the bug back

    An index is the dependable fix: marks[first] finds the element in whatever array the vector owns at that moment. reserve works only as long as nobody adds more elements than were reserved.

Nine mistakes cause most undefined behaviour, and a check finds each

Most undefined behaviour in real programs comes from a short list. Beside each cause is the check that finds it; most of them are flags you can add to any build today.

Cause, with an example The check that finds it
Reading or writing outside an array, such as v[v.size()], or a[10] for int a[10] AddressSanitizer, and a hardened standard library
Using an object after its lifetime: a pointer after delete, a reference into a vector that reallocated AddressSanitizer
A view of a temporary, such as a std::string_view of a temporary std::string AddressSanitizer, and Clang’s -Wdangling-gsl warning, which is on by default
Signed integer overflow, such as INT_MAX + 1 UndefinedBehaviorSanitizer (UBSan)
Reading an uninitialised variable, such as int total; total += 1; -Wall; in C++26 it becomes erroneous behaviour
Dereferencing a null pointer: *p when p is nullptr Usually a crash; UBSan names it
Two threads writing one variable without a lock, such as a shared int incremented by two threads ThreadSanitizer
Reading an object through the wrong type, such as a float read through a std::uint32_t* GCC’s -Wstrict-aliasing, part of -Wall, warns with -O2
Bad shifts and divisions: 1 << 32, x / 0, INT_MIN / -1 UBSan

Read down the right-hand column: AddressSanitizer covers the three mistakes with memory, UBSan the arithmetic and the null pointer, ThreadSanitizer the race, and warnings the two that remain. Unsigned arithmetic is not on the list: it wraps around by definition, so 4'294'967'295u + 1 is 0 everywhere. Signed arithmetic has no such promise, and that difference is behind the next two programs.

Checkpoint

Check: The usual causes and the checks that find them

  1. Question 1 of 2 Which check reports INT_MAX + 1 while the program runs?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: UndefinedBehaviorSanitizer, -fsanitize=undefined

    Signed overflow is arithmetic, not memory, so the memory checkers do not see it. UBSan instruments every signed addition, subtraction and multiplication and reports the first one that does not fit.

  2. Question 2 of 2 With a 32-bit int, which of these have undefined behaviour?

    Choose every answer that is right.

    Show the answer: Question 2 of 2

    Answer:

    • 1 << 32
    • INT_MIN / -1
    • INT_MAX + 1

    Signed overflow, oversized shifts and the one division whose result does not fit are on the lesson's list. Unsigned arithmetic has no undefined overflow, and C++20 defined shifting a 1 into the sign bit.

One file, four builds: the optimiser deletes an overflow check

This function guards a balance against overflow. The guard looks reasonable: if adding the amount made the balance smaller, the sum must have wrapped around.

deposit.cpp C++ · deposit.cpp
#include <cstdlib>
#include <limits>
#include <print>

// Adds a deposit unless the balance would overflow. The check relies on the sum wrapping
// around to a negative number, and signed arithmetic in C++ never promises that.
bool add_deposit(int& balance, int amount) {
    if (balance + amount < balance) return false;
    balance += amount;
    return true;
}

int main(int argc, char* argv[]) {
    int balance = std::numeric_limits<int>::max() - 5;
    int amount = argc > 1 ? std::atoi(argv[1]) : 10;
    bool accepted = add_deposit(balance, amount);
    std::println("accepted: {}, balance: {}", accepted, balance);
}

Here is the same file built four ways, with a balance 5 below the largest int and a deposit of 10:

One file, four builds Python · deposit_session.py
from session import run

# One source file, four builds: two compilers, without optimisation (-O0) and with it (-O2).
run("""
clang++ -std=c++23 -O0 deposit.cpp -o deposit && ./deposit
clang++ -std=c++23 -O2 deposit.cpp -o deposit && ./deposit
g++-16 -std=c++23 -O0 deposit.cpp -o deposit && ./deposit
g++-16 -std=c++23 -O2 deposit.cpp -o deposit && ./deposit
""")

Output

$ clang++ -std=c++23 -O0 deposit.cpp -o deposit && ./deposit
accepted: false, balance: 2147483642
$ clang++ -std=c++23 -O2 deposit.cpp -o deposit && ./deposit
accepted: true, balance: -2147483644
$ g++-16 -std=c++23 -O0 deposit.cpp -o deposit && ./deposit
accepted: true, balance: -2147483644
$ g++-16 -std=c++23 -O2 deposit.cpp -o deposit && ./deposit
accepted: true, balance: -2147483644

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 deposit_session.py

Only Apple clang at -O0 rejects the deposit. With -O2, and with GCC even at -O0, the guard is gone and the balance becomes negative. That is why “it worked on my machine” proves nothing in C++. Both compilers reasoned the same way: in a valid program balance + amount cannot overflow, so balance + amount < balance can only be true when amount is negative, and the test becomes amount < 0. For a deposit of 10 that is false, so the overflow the guard was meant to catch happens on the next line. Nothing in the program is “wrong” for the compiler; it kept every promise the standard makes. Step through that reasoning with the numbers of this run:

Interactive · stage by stage How an overflow guard turns into a test of the sign Step through the reasoning the optimiser applied to add_deposit, with the lesson's numbers, then the fixed function.
How an overflow guard turns into a test of the sign, step 7 of 7. Showing The guard as written (balance > max - amount), Overflow cannot happen, The test: amount < 0 (tbnz w1, #31), A deposit of 10 (2147483642 + 10), The outcome (rejected in every build). In focus: The guard as written.The guard as writtenbalance > max - amountOverflow cannot happensigned overflow is undefinedThe test: amount < 0tbnz w1, #31A deposit of 102147483642 + 10The outcomerejected in every build

The drawing shows the whole scene; its 7 steps are listed below.

Every step as text
  1. The idea. add_deposit tests whether adding amount made the balance smaller, which would mean the sum wrapped around. The call adds 10 to 2,147,483,642, five below the largest int.
  2. A rule as a fact. Signed overflow is undefined behaviour, so in a valid program balance + amount never wraps. The optimiser may treat that as a fact about every call.
  3. The rewrite. Without wrap-around the sum is smaller than balance only when amount is negative. The comparison becomes amount < 0, and balance is no longer part of it.
  4. In the machine code. The arm64 code that Apple clang wrote at -O2 starts with tbnz w1, #31: a jump on bit 31 of amount, its sign bit. GCC 16 made the same rewrite even at -O0.
  5. The deposit of 10. For a deposit of 10, amount < 0 is false, so the guard lets the deposit through and the next line adds 10 to a balance that has no room for it.
  6. Three builds accept. Three of the four builds printed accepted: true, balance: -2147483644. Only Apple clang at -O0 kept the comparison as written and rejected the deposit.
  7. Check before adding. deposit_fixed.cpp compares balance with max - amount before it adds, so no expression ever overflows. All four builds printed accepted: false, balance: 2147483642.

The machine code shows it:

What Apple clang made of add_deposit at -O2 Python · deposit_asm_session.py
from session import run

# The machine code Apple clang writes for add_deposit at -O2 (arm64), from the label of the function to its return.
run("""
clang++ -std=c++23 -O2 -S deposit.cpp -o deposit.s
sed -n '/^__Z11add_depositRii:/,/ret$/p' deposit.s
""")

Output

$ clang++ -std=c++23 -O2 -S deposit.cpp -o deposit.s
$ sed -n '/^__Z11add_depositRii:/,/ret$/p' deposit.s
__Z11add_depositRii:                    ; @_Z11add_depositRii
	.cfi_startproc
; %bb.0:
	tbnz	w1, #31, LBB0_2
; %bb.1:
	ldr	w8, [x0]
	add	w8, w8, w1
	str	w8, [x0]
LBB0_2:
	mvn	w8, w1
	lsr	w0, w8, #31
	ret

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 deposit_asm_session.py

On arm64, w1 holds amount and x0 the address of balance. The first instruction, tbnz w1, #31, jumps to the end when bit 31 of amount, its sign bit, is set. Otherwise the next three load the balance, add and store it. The last two compute the return value from the sign of amount alone. The balance is never compared with anything.

UndefinedBehaviorSanitizer points at the real bug, and the fixed function, which checks before it adds, behaves the same in every build:

deposit_fixed.cpp C++ · deposit_fixed.cpp
#include <cstdlib>
#include <limits>
#include <print>

// The same rule, checked before adding, so no expression ever overflows.
bool add_deposit(int& balance, int amount) {
    constexpr int max = std::numeric_limits<int>::max();
    constexpr int min = std::numeric_limits<int>::min();
    if (amount > 0 && balance > max - amount) return false;
    if (amount < 0 && balance < min - amount) return false;
    balance += amount;
    return true;
}

int main(int argc, char* argv[]) {
    int balance = std::numeric_limits<int>::max() - 5;
    int amount = argc > 1 ? std::atoi(argv[1]) : 10;
    bool accepted = add_deposit(balance, amount);
    std::println("accepted: {}, balance: {}", accepted, balance);
}
UBSan, then the fixed version in four builds Python · deposit_check_session.py
from session import run

# UndefinedBehaviorSanitizer names the overflow; the fixed version gives one answer in every build.
run("""
clang++ -std=c++23 -O2 -g -fsanitize=undefined deposit.cpp -o deposit && ./deposit
clang++ -std=c++23 -O0 deposit_fixed.cpp -o fixed && ./fixed
clang++ -std=c++23 -O2 deposit_fixed.cpp -o fixed && ./fixed
g++-16 -std=c++23 -O0 deposit_fixed.cpp -o fixed && ./fixed
g++-16 -std=c++23 -O2 deposit_fixed.cpp -o fixed && ./fixed
""")

Output

$ clang++ -std=c++23 -O2 -g -fsanitize=undefined deposit.cpp -o deposit && ./deposit
deposit.cpp:8:17: runtime error: signed integer overflow: 2147483642 + 10 cannot be represented in type 'int'
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior deposit.cpp:8:17
accepted: false, balance: 2147483642
$ clang++ -std=c++23 -O0 deposit_fixed.cpp -o fixed && ./fixed
accepted: false, balance: 2147483642
$ clang++ -std=c++23 -O2 deposit_fixed.cpp -o fixed && ./fixed
accepted: false, balance: 2147483642
$ g++-16 -std=c++23 -O0 deposit_fixed.cpp -o fixed && ./fixed
accepted: false, balance: 2147483642
$ g++-16 -std=c++23 -O2 deposit_fixed.cpp -o fixed && ./fixed
accepted: false, balance: 2147483642

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 deposit_check_session.py

Two details are worth noticing. UBSan reported the overflow and let the program go on, so it still exited with status 0: in a test suite, add -fno-sanitize-recover=undefined so that the first report fails the run. And in the instrumented build the guard happened to work again, because the instrumentation changed the code; a sanitizer finds the bug, it does not tell you how the release build behaves.

Programmer Calculator (Bitwise) Add 2147483642 and 10 at 32 bits, signed, to see the wrapped result -2147483644 and the overflow note: what the hardware does, which C++ does not promise for int.

Key idea

A check that relies on undefined behaviour can vanish from any build, so check before you compute, as the fixed function does: then no expression ever overflows.

Checkpoint

Check: Checks the optimiser may delete

  1. Question 1 of 3 Why may a compiler remove the test balance + amount < balance from add_deposit?

    Choose one answer.

    Show the answer: Question 1 of 3

    Answer: Signed overflow is undefined, so the compiler may assume the sum never wraps and simplify the test

    Optimisers use the rules as facts. A test that only makes sense after an overflow can be rewritten or deleted, because a valid program never overflows.

  2. Question 2 of 3 What did both compilers turn balance + amount < balance into?

    Choose one answer.

    Show the answer: Question 2 of 3

    Answer: amount < 0, which is false for a deposit of 10

    For a deposit of 10 the rewritten test is false, so the guard lets the deposit through and the addition overflows on the next line: three builds printed balance: -2147483644.

  3. Question 3 of 3 The UBSan build of deposit.cpp printed a runtime error and then its result. With which exit status did it end?

    Choose one answer.

    Show the answer: Question 3 of 3

    Answer: 0, because UBSan reports and goes on by default

    A report that does not fail the run is easy to miss in a test log. -fno-sanitize-recover=undefined makes the first UBSan report end the program with a failing status.

An uninitialised variable gives each build its own answer

An uninitialised variable is even less predictable. total below is never given a starting value, so it holds an indeterminate value: The value of a local variable of a type such as int, double or a pointer that was declared without an initialiser: whatever bits its memory held. Reading it is undefined behaviour in C++23. More in “Variables and initialisation: =, () and {}”:

uninit.cpp C++ · uninit.cpp
#include <print>

int total_of(int n) {
    int total;  // never given a value
    for (int i = 1; i <= n; ++i) total += i;
    return total;
}

int main() {
    std::println("total_of(3) = {}", total_of(3));
}
Six builds of one uninitialised variable Python · uninit_session.py
from session import run

# One uninitialised variable, six builds. The right answer would be 6.
run("""
clang++ -std=c++23 -O0 uninit.cpp -o uninit && ./uninit
clang++ -std=c++23 -O2 uninit.cpp -o uninit && ./uninit
g++-16 -std=c++23 -O0 uninit.cpp -o uninit && ./uninit
g++-16 -std=c++23 -O2 uninit.cpp -o uninit && ./uninit
# C++26 mode: GCC 16 gives the variable a fixed value; Apple clang 21 does not do this yet
g++-16 -std=c++26 -O0 uninit.cpp -o uninit && ./uninit
clang++ -std=c++26 -O0 uninit.cpp -o uninit && ./uninit
# The warning that points at the bug
clang++ -std=c++23 -Wall -c uninit.cpp -o uninit.o
""")

Output

$ clang++ -std=c++23 -O0 uninit.cpp -o uninit && ./uninit
total_of(3) = -98174298
$ clang++ -std=c++23 -O2 uninit.cpp -o uninit && ./uninit
total_of(3) = 0
$ g++-16 -std=c++23 -O0 uninit.cpp -o uninit && ./uninit
total_of(3) = 7
$ g++-16 -std=c++23 -O2 uninit.cpp -o uninit && ./uninit
total_of(3) = 6
# C++26 mode: GCC 16 gives the variable a fixed value; Apple clang 21 does not do this yet
$ g++-16 -std=c++26 -O0 uninit.cpp -o uninit && ./uninit
total_of(3) = 6
$ clang++ -std=c++26 -O0 uninit.cpp -o uninit && ./uninit
total_of(3) = -98174298
# The warning that points at the bug
$ clang++ -std=c++23 -Wall -c uninit.cpp -o uninit.o
uninit.cpp:5:34: warning: variable 'total' is uninitialized when used here [-Wuninitialized]
    5 |     for (int i = 1; i <= n; ++i) total += i;
      |                                  ^~~~~
uninit.cpp:4:14: note: initialize the variable 'total' to silence this warning
    4 |     int total;  // never given a value
      |              ^
      |               = 0
1 warning generated.

This output changes from run to run: The two Apple clang builds without optimisation print whatever was left in the memory of total, plus 6, so their number can change from run to run and from machine to machine.

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 uninit_session.py

The right answer is 6. The four C++23 builds print four different values, a large negative number, 0, 7 and 6: whatever was in that register or stack slot, or whatever the optimiser chose once it noticed the read. GCC at -O2 printing 6 is luck, not correctness. The -Wall warning at the end finds the bug in one line, which is a good reason to build with warnings on every time. Here are the six runs side by side:

Build total_of(3) printed
Apple clang 21, C++23, -O0 −98174298
Apple clang 21, C++23, -O2 0
GCC 16, C++23, -O0 7
GCC 16, C++23, -O2 6
GCC 16, C++26, -O0 6
Apple clang 21, C++26, -O0 −98174298

The first four rows are one bug and four answers. The last two are the next section’s subject: C++26 changes what this read means, and of the two compilers only GCC 16 already does it.

Expecting a local int to start at zero

int total; inside a function gets no starting value: four C++23 builds gave it four different ones. Objects with static storage duration, such as globals, are set to zero before the program starts; a local variable is not. Write int total = 0;, which every build and every standard agree on.

Checkpoint

Check: Reading an uninitialised variable

  1. Question 1 of 2 What is the right fix for total_of in uninit.cpp?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: Write int total = 0;

    The bug is the missing starting value, so the fix is to give it one. The warning -Wall printed points at the same line and suggests the same initialiser.

  2. Question 2 of 2 GCC 16 at -O2 printed total_of(3) = 6, the right answer. What does that run show?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Nothing about correctness, because other builds of the same file printed other values

    A right answer from code with undefined behaviour is luck, not correctness. Four C++23 builds gave four answers, and only the initialiser makes all of them agree.

C++26 makes two kinds of undefined behaviour less dangerous

C++26 does not remove undefined behaviour, but it makes two common kinds of it less dangerous. Walk through the rules this lesson has met, standard by standard, before the two changes in detail:

Timeline · 5 events in order The rules for the bugs of this lesson, standard by standard Walk through the standards in order. Each event is one rule this lesson relies on, and what changed in it.
  1. C++20

    Two's complement, but overflow still undefined representation

    C++20 fixed how signed integers are stored, as two's complement, and made 1 << 31 well defined: it is the smallest int. An arithmetic result that does not fit its type stayed undefined, which is why the deposit guard could vanish.

  2. C++23 and earlier

    An uninitialised read is undefined behaviour

    Up to and including C++23, reading a local int that was never given a value is undefined behaviour. The four C++23 builds of uninit.cpp printed -98174298, 0, 7 and 6.

  3. C++26: reads

    Erroneous behaviour for uninitialised reads P2795R5

    The read gives an erroneous value instead: the program stays predictable, the code is still wrong, and compilers are encouraged to diagnose it. [[indeterminate]] marks a variable left uninitialised on purpose. GCC 16 implements it; Apple clang 21 does not yet.

  4. C++26: library

    A hardened standard library P3471R4

    A hardened implementation checks preconditions such as the index of operator[] and front() on an empty container while the program runs. In the hardened builds of both libraries, a failed check stops the program instead of corrupting memory.

  5. C++26: unchanged

    Still undefined behaviour

    Raw pointers, use after free, data races and signed overflow stay undefined in C++26, so sanitizers are still the way to find them.

The timeline has 5 events, from C++20 to C++26: unchanged.

Uninitialised reads become erroneous behaviour

Reading a local variable that was never initialised is no longer undefined but erroneous behaviour: C++26's name for reading an uninitialised local variable: the variable holds a value the implementation chooses, the program goes on predictably, and compilers are encouraged to diagnose the read. The code is still a bug. More in “Variables and initialisation: =, () and {}”: the variable holds an erroneous value, the read is well defined but still a bug, and compilers are encouraged to diagnose it. A variable whose indeterminate value is wanted on purpose, for example a large buffer that is filled later, can opt out with the attribute [[indeterminate]].

Version note

GCC 16 implements erroneous behaviour for uninitialised reads: in C++26 mode it zero-initialises such local variables unless -ftrivial-auto-var-init says otherwise, which is why -std=c++26 printed 6 at -O0. Clang’s status page lists the feature as not implemented, and Apple clang 21 printed the same value in C++23 and C++26 mode. Write int total = 0; either way: the new rule makes the bug predictable, not correct.

A hardened library stops a read past the end

A hardened standard library: A standard library that checks the preconditions of calls such as operator[] and front() while the program runs, and stops it when one fails, as libc++'s hardening modes and libstdc++ with _GLIBCXX_ASSERTIONS do. C++26 makes such hardened implementations part of the standard. More in “std::vector: the container to reach for first” of the standard library checks some preconditions of its functions while the program runs, mainly the ones that prevent reading or writing out of bounds: the index of operator[] on std::vector, std::span, std::string and std::string_view, front() and back() on an empty container, and the value of an empty std::optional. Breaking one of them becomes a contract violation; in the hardened builds that both libraries already offer, a violation stops the program instead of corrupting memory. How you turn hardening on is left to each toolchain:

bounds.cpp C++ · bounds.cpp
#include <print>
#include <vector>

int main() {
    std::vector<int> marks{70, 80, 90};
    std::size_t i = marks.size();  // one past the last element
    std::println("marks[{}] = {}", i, marks[i]);
}
One read past the end, with and without the library's checks Python · bounds_session.py
from session import run

# Reading one element past the end, with the standard libraries' checks off and on.
run("""
clang++ -std=c++23 -O2 bounds.cpp -o bounds && ./bounds
g++-16 -std=c++23 -O2 bounds.cpp -o bounds && ./bounds
g++-16 -std=c++23 -O0 bounds.cpp -o bounds && ./bounds
clang++ -std=c++23 -O2 -D_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_FAST bounds.cpp -o bounds && ./bounds
clang++ -std=c++23 -O2 -D_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_DEBUG bounds.cpp -o bounds && ./bounds
""")

Output

$ clang++ -std=c++23 -O2 bounds.cpp -o bounds && ./bounds
marks[3] = 0
$ g++-16 -std=c++23 -O2 bounds.cpp -o bounds && ./bounds
marks[3] = 0
$ g++-16 -std=c++23 -O0 bounds.cpp -o bounds && ./bounds
…/c++/16/bits/stl_vector.h:1253: constexpr std::vector< <template-parameter-1-1>, <template-parameter-1-2> >::reference std::vector< <template-parameter-1-1>, <template-parameter-1-2> >::operator[](size_type) [with _Tp = int; _Alloc = std::allocator<int>; reference = int&; size_type = long unsigned int]: Assertion '__n < this->size()' failed.
Abort trap: 6
[exit status 134]
$ clang++ -std=c++23 -O2 -D_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_FAST bounds.cpp -o bounds && ./bounds
Trace/BPT trap: 5
[exit status 133]
$ clang++ -std=c++23 -O2 -D_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_DEBUG bounds.cpp -o bounds && ./bounds
…/c++/v1/__vector/vector.h:414: libc++ Hardening assertion __n < size() failed: vector[] index out of bounds
Abort trap: 6
[exit status 134]

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 bounds_session.py

Without checks both libraries return a value for marks[3], here 0, as if it existed. GCC’s library checks operator[] by default when you compile without optimisation, so the -O0 build stops with a message naming the failed condition; the -O2 build drops the check. libc++’s fast mode stops the program with a trap and no message, exit status 133 (128 plus signal 5, the trap signal), and its debug mode prints which check failed. The fast mode is designed to be cheap enough for release builds.

Version note

The libstdc++ manual describes _GLIBCXX_ASSERTIONS as defined by default when compiling with no optimisation; define it yourself, or _GLIBCXX_NO_ASSERTIONS to opt out. In libc++ choose a mode with -D_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_FAST, _EXTENSIVE or _DEBUG.

Neither change covers raw pointers, use after free, data races or signed overflow. Those stay undefined in C++26, and sanitizers are still the way to find them.

Checkpoint

Check: What C++26 changes

  1. Question 1 of 2 In C++26, what is reading a local int that was never initialised?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: Erroneous behaviour: a defined value, still a bug, which compilers are encouraged to diagnose

    Erroneous behaviour keeps the meaning of the run, so an optimiser may no longer assume the read never happens, while still treating it as a bug that tools should report.

  2. Question 2 of 2 bounds.cpp reads marks[3] from a vector of three marks. Which of these builds stopped the program?

    Choose every answer that is right.

    Show the answer: Question 2 of 2

    Answer:

    • clang++ at -O2 with the libc++ fast hardening mode
    • clang++ at -O2 with the libc++ debug hardening mode
    • g++-16 at -O0

    A hardened library turns the read past the end into a stop instead of a quiet wrong value. Which builds are hardened is up to the toolchain and its options.

Practise: spot the undefined behaviour

Each question below shows one short snippet, and the session opens with the idea your earlier answers left weakest. In every snippet, int is 32 bits wide, as it is on the compilers of this track. Decide before you check, and read the explanation even when you are right. The snippets come from every part of this lesson, from the table of nine causes to the two C++26 changes, and each explanation names the rule that decides the case, so a wrong answer tells you which section to reread.

Practice that adapts to you

Spot the undefined behaviour

19 questions about 7 ideas of this lesson. Each answer is explained at once, and what you get right is kept in this browser.

  1. Question 1 of 19 sizeof(int) is 4 on both compilers of this track, and may be another size elsewhere. What kind of behaviour is that?

    Choose one answer.

    Show the answer: Question 1 of 19

    Answer: Implementation-defined, because each compiler picks the size and documents it

    sizeof(int) is implementation-defined: chosen by each compiler, documented and safe to use, although portable code should not assume 4.

  2. Question 2 of 19 constexpr_ub.cpp failed to compile because one_more(std::numeric_limits<int>::max()) initialised a constexpr variable. What happens if main makes the same call while the program runs?

    Choose one answer.

    Show the answer: Question 2 of 19

    Answer: It compiles without a word, and the addition is undefined behaviour when it runs

    The compiler must catch undefined behaviour in a constant expression, which it evaluates itself. The same function called at run time compiles without a word, which is why the lesson calls this the one place where the compiler must catch it for you.

  3. Question 3 of 19 lifetime.cpp prints begin global before main starts. When does the global object end?

    Choose one answer.

    Show the answer: Question 3 of 19

    Answer: After main has returned, so end global is the last line

    Static storage duration covers the whole run: the global began before main and ended after it, the first and the last line of the output.

  4. Question 4 of 19 Does printing name have undefined behaviour?

    Read the code, then choose one answer.

    std::string_view name = std::string("Asha") + " Rao";
    std::println("{}", name);
    Show the answer: Question 4 of 19

    Answer: Yes. The std::string built on the first line is a temporary that dies at the end of that line

    A std::string_view only points at characters; it owns nothing. The temporary string is destroyed at the end of the full expression, so name points into freed memory. Lifetime extension applies when a reference is bound directly to a temporary, never to a view. Store a std::string when you need to keep the text.

  5. Question 5 of 19 Why does a push_back on a full vector leave references to its elements dangling?

    Choose one answer.

    Show the answer: Question 5 of 19

    Answer: It allocates a bigger array, moves the elements across and frees the old one

    The relocate session showed it with Tracer elements: begin C, then A and B moved into the new array, then the old A and B ended. Anything that pointed at the old A or B now dangles.

  6. Question 6 of 19 Does the last line have undefined behaviour?

    Read the code, then choose one answer.

    std::vector<int> v{1, 2, 3};   // size 3, capacity 3
    int* p = &v[0];
    v.push_back(4);
    std::println("{}", *p);
    Show the answer: Question 6 of 19

    Answer: Yes. push_back needed more room, moved the elements to a new array and freed the old one

    With no spare capacity, push_back reallocates, which invalidates every pointer, reference and iterator to the elements. p still holds the old address, where no object lives any more. Keep an index instead, or take the pointer again after the call.

  7. Question 7 of 19 Does this loop have undefined behaviour?

    Read the code, then choose one answer.

    int scores[5] = {};
    for (int i = 0; i <= 5; ++i) scores[i] = 10;
    Show the answer: Question 7 of 19

    Answer: Yes. The last pass writes scores[5], one element past the end of the array

    An array of 5 elements has indexes 0 to 4. The condition i <= 5 lets the loop write scores[5], memory that belongs to something else. The compiler does not have to warn, and the program may seem to work. Write the loop as i < 5, or better, as a range-for loop.

  8. Question 8 of 19 Does the addition have undefined behaviour?

    Read the code, then choose one answer.

    unsigned int u = 4'294'967'295u;  // the largest 32-bit unsigned value
    u = u + 1;
    Show the answer: Question 8 of 19

    Answer: No. Unsigned arithmetic wraps around, so u becomes 0

    Unsigned integer types do arithmetic modulo 2 to the power of their width, so the result is always defined: here it is 0. Only signed overflow is undefined. A wrap can still be a bug in your logic, which is why Clang offers -fsanitize=unsigned-integer-overflow as an extra check outside -fsanitize=undefined.

  9. Question 9 of 19 Does the addition have undefined behaviour?

    Read the code, then choose one answer.

    int big = 2'147'483'647;  // the largest 32-bit int
    big = big + 1;
    Show the answer: Question 9 of 19

    Answer: Yes. The result does not fit in an int, so this is signed overflow

    C++20 fixed how signed integers are represented, but it did not make overflow defined: an arithmetic result that is out of range for its type is still undefined behaviour. An optimiser may assume it never happens, which is exactly what broke the overflow check in deposit.cpp.

  10. Question 10 of 19 Does the second line have undefined behaviour?

    Read the code, then choose one answer.

    std::vector<int> v;
    int first = v.front();
    Show the answer: Question 10 of 19

    Answer: Yes. front() requires a vector that is not empty

    front() has a precondition: the vector must not be empty. Breaking it is undefined behaviour, and nothing is thrown. Hardened builds of the standard libraries check this precondition and stop the program; at() is the member function that checks and throws, but there is no checked front().

  11. Question 11 of 19 In C++20 and later, does this shift have undefined behaviour?

    Read the code, then choose one answer.

    int bits = 1 << 31;
    Show the answer: Question 11 of 19

    Answer: No. Since C++20 the result is the value congruent modulo 2 to the 32nd, which is -2147483648

    C++20 defines E1 << E2 as the value congruent to E1 times 2 to the E2 modulo 2 to the N, so 1 << 31 is the smallest int. A shift is undefined when the shift count is negative or at least the width of the type: 1 << 32 is still undefined behaviour.

  12. Question 12 of 19 Does the second line have undefined behaviour?

    Read the code, then choose one answer.

    float f = 1.5f;
    std::uint32_t bits = *reinterpret_cast<std::uint32_t*>(&f);
    Show the answer: Question 12 of 19

    Answer: Yes. It reads a float object through a glvalue of type std::uint32_t, which the aliasing rule forbids

    The standard lets you read an object only through its own type, its signed or unsigned twin, or a character type such as unsigned char or std::byte. Optimisers rely on that rule. std::bit_cast<std::uint32_t>(f) copies the bytes into a new uint32_t and is well defined; the memory layout lesson uses it.

  13. Question 13 of 19 Does this loop have undefined behaviour?

    Read the code, then choose one answer.

    int a[4] = {1, 2, 3, 4};
    int total = 0;
    for (int* p = a; p != a + 4; ++p) total += *p;
    Show the answer: Question 13 of 19

    Answer: No. A pointer one past the last element may be formed and compared, as long as it is never dereferenced

    Pointer arithmetic may produce any position inside the array or one past its end, and that end pointer can be compared. The loop stops before dereferencing it, so it reads exactly the 4 elements. Forming a + 5, or reading *(a + 4), would be undefined behaviour.

  14. Question 14 of 19 In the -O2 code of add_deposit, what does the first instruction, tbnz w1, #31, LBB0_2, test?

    Choose one answer.

    Show the answer: Question 14 of 19

    Answer: Bit 31 of amount, its sign bit

    The machine code is the rewritten guard: a test of amount's sign, then the load, the addition and the store. Nothing in it compares the sum with the balance.

  15. Question 15 of 19 An overflow guard passes every test in a build without optimisation. Does that show it is safe?

    Choose one answer.

    Show the answer: Question 15 of 19

    Answer: No. A check that relies on undefined behaviour can vanish in any build; GCC removed this one even at -O0

    Four builds of deposit.cpp gave two answers. Only a guard that never overflows, such as the fixed function's, behaves the same in all of them.

  16. Question 16 of 19 Compiled as C++23, what does reading x mean?

    Read the code, then choose one answer.

    int x;
    std::println("{}", x);
    Show the answer: Question 16 of 19

    Answer: Undefined behaviour, because x has an indeterminate value

    A local int without an initialiser has an indeterminate value, and reading it is undefined behaviour up to C++23; compilers warn with -Wall. C++26 turns this particular case into erroneous behaviour: the read gives some defined value, but it is still a bug. Write int x = 0; or give x its real value.

  17. Question 17 of 19 Apple clang at -O2 printed total_of(3) = 0. Which explanation fits?

    Choose one answer.

    Show the answer: Question 17 of 19

    Answer: With the read undefined, the optimiser was free to produce any value, and this build produced 0

    Each build met the same undefined read and did something different with it. None of the four values says anything about what another build, or the next compiler version, will print.

  18. Question 18 of 19 What does a hardened standard library do when operator[] of a std::vector gets an index past the end?

    Choose one answer.

    Show the answer: Question 18 of 19

    Answer: It stops the program instead of reading memory out of bounds

    Hardening checks preconditions such as the index of operator[] while the program runs. libc++'s fast mode stopped bounds.cpp with exit status 133, and its debug mode said which check failed.

  19. Question 19 of 19 Which of these are still undefined behaviour in C++26?

    Choose every answer that is right.

    Show the answer: Question 19 of 19

    Answer:

    • Using memory after it was freed
    • Two threads writing one variable without a lock
    • Signed integer overflow

    C++26 changes two things: uninitialised local reads become erroneous behaviour, and the standard library may be hardened. Raw pointers, use after free, data races and signed overflow stay undefined.

Interview questions

Fresher · What is erroneous behaviour in C++26, and how is it different from undefined behaviour?

Erroneous behaviour is a new category in C++26 for code that is definitely wrong but still has a defined result. Its first use is reading an uninitialised local variable: up to C++23 that was undefined behaviour, so the optimiser could assume it never happened and anything could follow. In C++26 the variable holds an erroneous value instead, the read gives that value, and compilers are encouraged to diagnose it. The difference matters: undefined behaviour takes away the meaning of the whole run, while erroneous behaviour keeps the program predictable until the bug is found. GCC 16 implements it by zero-initialising such variables in -std=c++26 mode; Clang does not yet. It is still a bug, and the attribute [[indeterminate]] marks a variable left uninitialised on purpose.

An interviewer who hears this answer often asks two more questions. Choose the answer you would give to each, and the feedback says what it gets right or leaves out:

Checkpoint

Interview round: two follow-up questions

  1. Question 1 of 2 Interview follow-up: GCC 16 in C++26 mode printed 6, the right answer, for uninit.cpp. Why is int total; still a bug there?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: The 0 is the compiler's choice, not the program's, so the code is right only by accident, and compilers are encouraged to report the read

    Erroneous behaviour makes the bug predictable, not correct. A good answer names the difference from undefined behaviour and still writes int total = 0.

  2. Question 2 of 2 Interview follow-up: when would you write [[indeterminate]] on a local variable?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: On a large buffer that the code fills before it reads it, when the value C++26 would give it first is not wanted

    [[indeterminate]] opts one variable out of erroneous behaviour. Use it only where filling the variable first would be wasted work and the code is sure to write it before it reads it.

The module’s bank keeps two longer questions about this lesson, with their first steps: a team that adds three compiler flags to make undefined behaviour safe, and an overflow guard that passes in debug builds:

Model answers open with any pass: ₹79 for 1 week ($2.99), one payment that never renews.

  1. Mid to senior

    To "make undefined behaviour safe", a team adds -fwrapv, -fno-strict-aliasing and -ftrivial-auto-var-init=zero to its release build. What does each flag change, what does it hide, and what would you recommend instead?

    Model answer, Pro. Model answers open with any pass; prices are in the notice on this page. First step and follow-ups

  2. Fresher to mid

    Code review approves if (balance + amount < balance) return false; as an overflow guard for an int balance, and the tests pass in debug builds. Explain how the guard can disappear, how you would prove it, and how to write the check correctly.

    Model answer, Pro. First step and follow-ups

Key takeaways

  • An object’s lifetime runs from the end of its initialisation to the start of its destructor or the release of its memory. A pointer or reference that outlives its object dangles, and using it is undefined behaviour.
  • Undefined behaviour means the standard places no requirements on the whole run: a crash, a wrong answer and a correct-looking answer are all allowed, and none of them has to be repeatable.
  • push_back on a full vector reallocates and invalidates every reference, pointer and iterator to its elements; keep indexes, take references after insertions, or use a container whose references stay valid.
  • Optimisers treat the rules as facts. An overflow check written as balance + amount < balance disappears at -O2 in Apple clang and in GCC already at -O0; check before you compute instead.
  • An uninitialised variable gave four C++23 builds four different answers. Build with -Wall, and run tests with sanitizers and a hardened standard library: they catch what a passing run cannot.
  • C++26 makes uninitialised local reads erroneous behaviour and adds standard library hardening. Signed overflow, dangling pointers and data races remain undefined.

Terms in this lesson

implementation-defined behaviour
Behaviour that the C++ standard leaves to each implementation, which must document its choice, such as sizeof(int). A program that relies on it is valid, but may give other results with another compiler or platform.
iterator invalidation
What happens to the iterators, pointers and references into a container after an operation that moves or removes its elements, such as a push_back that reallocates or an erase: they no longer refer to valid elements, and using them is undefined behaviour.
lifetime
The part of a run during which an object exists: it begins once memory of the right size and alignment is obtained and the object's initialisation is complete, and ends when its destructor starts or its memory is released or reused.
undefined behaviour
What a program does when it breaks a rule for which the C++ standard sets no requirements, such as reading past the end of an array. The compiler may assume it never happens, so the result can change with the compiler and the optimisation level.

Corrections

  • The hardening section now says that a failed check stops the program in the hardened builds that both standard libraries offer.
  • The table of the uninitialised variable now matches the recorded run; the number the Apple clang builds print can differ from run to run and from machine to machine.

References

Related tools

Report a problem with this lesson

Quick answers and tool search

Type to search tools or to get a quick answer, for example 18% of 2500. Use the up and down arrow keys to move through the results, Enter to choose, and Escape to close.