Skip to content
binshelf/ cpp

Search lessons

Type a C++ term, like vector, reference, unique_ptr or use-after-free.

    Lessons

    On this page

    1. Key terms
    2. In 30 seconds
    3. What undefined behavior is, and why C++ has it
    4. A catalogue of undefined behavior
    5. Arithmetic
    6. Memory
    7. How optimizations exploit undefined behavior
    8. assert: check your own rules
    9. NDEBUG turns asserts off
    10. static_assert: check while compiling
    11. Which one should I use?
    12. A checklist of habits
    13. Under the hood
    14. Common pitfalls
    15. Doing real work inside assert
    16. Assuming a build without sanitizers proves the code is fine
    17. Try it yourself

    Module 5 · Errors and undefined behavior

    5.3Undefined behavior, assertions and sanitizers

    Every kind of undefined behavior from earlier lessons in one place, each caught by a sanitizer. See how an optimized build can quietly change what buggy code does, and catch your own mistakes with assert and static_assert.

    About 30 minutesIntermediate

    On this page
    1. Key terms
    2. In 30 seconds
    3. What undefined behavior is, and why C++ has it
    4. A catalogue of undefined behavior
    5. Arithmetic
    6. Memory
    7. How optimizations exploit undefined behavior
    8. assert: check your own rules
    9. NDEBUG turns asserts off
    10. static_assert: check while compiling
    11. Which one should I use?
    12. A checklist of habits
    13. Under the hood
    14. Common pitfalls
    15. Doing real work inside assert
    16. Assuming a build without sanitizers proves the code is fine
    17. Try it yourself

    Key terms

    undefined behavior
    Code the C++ rules give no meaning to. The compiler doesn't have to catch it, and the program might crash, print garbage or seem to work.
    implementation-defined
    Behavior the standard lets each compiler choose, as long as it documents the choice, like the size of long. Unlike undefined behavior, the result is reliable on a given platform.
    optimization level (-O0, -O2)
    How hard the compiler's optimizer works to make the program fast. It rewrites your code into faster code that gives the same result, assuming no undefined behavior happens. -O0 (the default) barely optimizes; -O2 is the usual level for release builds.
    assert(condition)
    From <cassert>: checks a condition while the program runs. If it's false, it prints the condition, file and line, and stops the program.
    NDEBUG
    A name that, when defined (with #define NDEBUG or the flag -DNDEBUG), turns every assert into nothing. Release builds usually define it.
    precondition
    Something that must be true when a function is called, like "count is greater than 0". Breaking it is a bug in the caller.
    static_assert(condition)
    Checks a condition while compiling. If it's false, the program doesn't compile.
    library assertions
    Checks built into the standard library itself, such as an index check in a vector's []. GCC's library runs them when _GLIBCXX_ASSERTIONS is defined, which version 15 does for you in builds without optimization.

    Many lessons so far ended with a sanitizer report: an int that overflowed, an index one past the end, a reference to freed memory. Each was undefined behavior, and each was caught only because the program ran with sanitizers. This lesson puts all of them in one place, shows why undefined behavior is worse than a crash, and adds two tools for catching your own mistakes: assert and static_assert.

    In 30 seconds

    • Undefined behavior is code the C++ rules give no meaning to. The compiler assumes it never happens, and builds the program on that assumption.
    • So an optimized build can do something your code doesn’t seem to say. Don’t reason about what buggy code “will do”; find the bug.
    • AddressSanitizer and UndefinedBehaviorSanitizer catch the common kinds while you test. Warnings catch some before you run.
    • assert(condition) checks your own rules while the program runs, until -DNDEBUG removes it. static_assert(condition) checks them while compiling.

    What undefined behavior is, and why C++ has it

    The C++ standard says what every correct program does. For some mistakes, it says nothing at all: reading past the end of an array, overflowing an int, using freed memory. That’s undefined behavior. The program might crash, print garbage, or seem to work today and fail after an unrelated change.

    C++ leaves these cases undefined on purpose. Checking every index, every addition and every pointer would cost time on every operation, in every program, including the correct ones. Different CPUs also do different things on overflow or a bad address. So the standard makes a deal: you promise not to do these things, and the compiler produces fast code for the cases you do write.

    Undefined behavior isn’t the same as implementation-defined behavior. sizeof(long) is 8 on 64-bit Linux and 4 on 64-bit Windows, but each compiler documents its answer and sticks to it. Undefined behavior has no answer at all, not even a documented one.

    A catalogue of undefined behavior

    These are the kinds you’ve met, with where each one was first shown, plus two that are new here: integer division by zero, and using a variable after its block ended. Each one gets a fresh example below, caught by the sanitizers the course uses (-fsanitize=address,undefined). The last row is the exception: no sanitizer in this setup catches it.

    KindExampleCaught byFirst shown in
    Signed integer overflowint sum past about 2.1 billionUBSanSetting up, Numbers
    Integer division by zerototal / count with count == 0UBSanthis lesson
    Shifting too far1u << 32 on a 32-bit valueUBSanOperators
    Out of boundsa[4] in a 4-element arrayASan, UBSanSetting up, Control flow, Arrays and span
    Null pointer dereference*p with p == nullptrUBSanPointers
    Use after freea reference into a vector that grewASanReferences, RAII
    Use after scopea pointer to a variable whose block endedASanthis lesson (lifetimes: Stack, heap and lifetime)
    Double freedelete twiceASanRAII, Smart pointers
    new[] with deletethe wrong form of deleteASanRAII
    Uninitialized variablereading int x; before setting itwarnings (simple cases only)Variables

    Arithmetic

    Overflowing a signed integer, dividing an integer by zero, and shifting by the width of the type or more. UndefinedBehaviorSanitizer (UBSan) checks each one:

    #include <print>
    
    int reads = 20'000'000;
    int read_length = 150;
    int total_bases = reads * read_length; // 3 billion doesn't fit in an int
    std::println("{}", total_bases);

    This fails when it runs

    main.cpp:5:25: runtime error: signed integer overflow: 20000000 * 150 cannot be represented in type 'int'
    #include <print>
    
    int total_length = 1500;
    int read_count = 0;
    std::println("{}", total_length / read_count);

    This fails when it runs

    main.cpp:5:33: runtime error: division by zero
    #include <cstdint>
    #include <print>
    
    std::uint64_t one = 1;
    int position = 64;
    std::println("{}", one << position);

    This fails when it runs

    main.cpp:6:24: runtime error: shift exponent 64 is too large for 64-bit type 'long unsigned int'

    Unsigned integers don’t overflow in the undefined sense: they wrap around, as Numbers showed. Shifting them too far is still undefined.

    Memory

    Reading outside an allocation, following a null pointer, and using memory after its lifetime ended. AddressSanitizer (ASan) keeps track of which bytes the program may use and catches most of these; UBSan reports the null pointer:

    #include <print>
    #include <vector>
    
    std::vector<float> pixels(3);
    float* p = pixels.data();
    std::println("{}", p[3]); // one past the last pixel

    This fails when it runs

    ERROR: AddressSanitizer: heap-buffer-overflow on address 0x…
    READ of size 4 at 0x… thread T0
        #0 std::basic_format_arg<std::basic_format_context<std::__format::_Sink_iter<char>, char> >::basic_format_arg<float>(float&)
           … 6 frames inside the standard library
        #7 main main.cpp:6
    
    0x… is located 0 bytes after 12-byte region [0x…,0x…)
    allocated by thread T0 here:
        #0 operator new(unsigned long)
           … 7 frames inside the standard library
        #8 main main.cpp:4
    
    SUMMARY: AddressSanitizer: heap-buffer-overflow main.cpp:6 in main
    #include <print>
    
    const char* name = nullptr;
    char first = *name;
    std::println("{}", first);

    This fails when it runs

    main.cpp:4:14: runtime error: load of null pointer of type 'const char'
    #include <print>
    
    int* count = new int(42);
    delete count;
    std::println("{}", *count);

    This fails when it runs

    ERROR: AddressSanitizer: heap-use-after-free on address 0x…
    READ of size 4 at 0x… thread T0
        #0 std::basic_format_arg<std::basic_format_context<std::__format::_Sink_iter<char>, char> >::basic_format_arg<int>(int&)
           … 6 frames inside the standard library
        #7 main main.cpp:5
    
    0x… is located 0 bytes inside of 4-byte region [0x…,0x…)
    freed by thread T0 here:
        #0 operator delete(void*, unsigned long)
        #1 main main.cpp:4
    
    previously allocated by thread T0 here:
        #0 operator new(unsigned long)
        #1 main main.cpp:3
    
    SUMMARY: AddressSanitizer: heap-use-after-free main.cpp:5 in main
    #include <print>
    
    int* best = nullptr;
    {
        int score = 42;
        best = &score;
    } // score's lifetime ends here
    std::println("{}", *best);

    This fails when it runs

    ERROR: AddressSanitizer: stack-use-after-scope on address 0x…
    READ of size 4 at 0x… thread T0
        #0 std::basic_format_arg<std::basic_format_context<std::__format::_Sink_iter<char>, char> >::basic_format_arg<int>(int&)
           … 6 frames inside the standard library
        #7 main main.cpp:8
    
    Address 0x… is located in stack of thread T0 at offset 48 in frame
        #0 main main.cpp
    
      This frame has 2 object(s):
        [48, 52) 'score' (line 6) <== Memory access at offset 48 is inside this variable
        [64, 80) '<unknown>'
          (longjmp and C++ exceptions *are* supported)
    SUMMARY: AddressSanitizer: stack-use-after-scope main.cpp:8 in main
    int* buffer = new int[4]{};
    int* alias = buffer;
    delete[] buffer;
    delete[] alias; // the same memory again

    This fails when it runs

    ERROR: AddressSanitizer: attempting double-free on 0x… in thread T0:
        #0 operator delete[](void*)
        #1 main main.cpp:4
    
    0x… is located 0 bytes inside of 16-byte region [0x…,0x…)
    freed by thread T0 here:
        #0 operator delete[](void*)
        #1 main main.cpp:3
    
    previously allocated by thread T0 here:
        #0 operator new[](unsigned long)
        #1 main main.cpp:1
    
    SUMMARY: AddressSanitizer: double-free main.cpp:4 in main
    float* make_buffer(int n) {
        return new float[n]{};
    }
    
    int main() {
        float* pixels = make_buffer(4);
        delete pixels; // needs delete[]
    }

    This fails when it runs

    ERROR: AddressSanitizer: alloc-dealloc-mismatch (operator new [] vs operator delete) on 0x…
        #0 operator delete(void*, unsigned long)
        #1 main main.cpp:7
    
    0x… is located 0 bytes inside of 16-byte region [0x…,0x…)
    allocated by thread T0 here:
        #0 operator new[](unsigned long)
        #1 make_buffer(int) main.cpp:2
        #2 main main.cpp:6
    
    SUMMARY: AddressSanitizer: alloc-dealloc-mismatch main.cpp:7 in main
    HINT: if you don't care about these errors you may set ASAN_OPTIONS=alloc_dealloc_mismatch=0

    A few kinds aren’t caught by these two sanitizers. Reading an uninitialized variable is one: GCC and Clang warn about simple cases (with -Werror, they don’t compile), and Clang’s separate MemorySanitizer finds most of the rest. Data races between threads need ThreadSanitizer; a later module covers threads.

    Key ideaOne more checker: the library's own

    GCC’s standard library has checks of its own (_GLIBCXX_ASSERTIONS), and version 15, the one used here, turns them on in builds without optimization. So v[3] on a 3-element std::vector, or * on an empty std::optional, stops with a failed “Assertion” instead of a sanitizer report. At -O2 they’re off unless you define _GLIBCXX_ASSERTIONS yourself (-D_GLIBCXX_ASSERTIONS), and other standard libraries have their own settings.

    #include <print>
    #include <vector>
    
    std::vector<int> lengths = {150, 151, 149};
    std::println("{}", lengths[3]);

    This fails when it runs

    /usr/include/c++/15/bits/stl_vector.h:1263: 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.

    How optimizations exploit undefined behavior

    This function tries to detect an overflow by doing the addition and checking whether the result went down:

    #include <iostream>
    #include <print>
    
    bool add_overflows(int count, int extra) {
        int total = count + extra;
        return total < count;
    }
    
    int main() {
        int count = 0;
        std::cin >> count;
        std::println("{}", add_overflows(count, 100));
    }

    Output

    true

    Built without optimization (-O0, the default) and without sanitizers, the addition happened to wrap around to a negative number in this build, so the check said true. Nothing promises that: the overflow is undefined behavior, and this answer is luck, not a rule. (The input comes from standard input so that the compiler can’t work out the answer while compiling.) Now the same program, unchanged, built with -O2:

    #include <iostream>
    #include <print>
    
    bool add_overflows(int count, int extra) {
        int total = count + extra;
        return total < count;
    }
    
    int main() {
        int count = 0;
        std::cin >> count;
        std::println("{}", add_overflows(count, 100));
    }

    Output

    false

    GCC’s optimizer reasons: signed overflow can’t happen in a valid program, so count + extra < count is true only when extra is negative. It replaces the whole function with that test. With extra equal to 100, the check is always false, and the overflow goes unnoticed. Neither output is the “real” answer, because the program doesn’t have one. The compiler did its job both times; the program is what’s wrong. With the sanitizers on, the addition itself is reported:

    #include <iostream>
    #include <print>
    
    bool add_overflows(int count, int extra) {
        int total = count + extra;
        return total < count;
    }
    
    int main() {
        int count = 0;
        std::cin >> count;
        std::println("{}", add_overflows(count, 100));
    }

    This fails when it runs

    main.cpp:5:9: runtime error: signed integer overflow: 2147483600 + 100 cannot be represented in type 'int'

    The fix is to check before the addition, so no overflow ever happens. std::numeric_limits<int>::max() is the largest int:

    #include <iostream>
    #include <limits>
    #include <print>
    
    bool add_overflows(int count, int extra) { // extra must not be negative
        return count > std::numeric_limits<int>::max() - extra;
    }
    
    int main() {
        int count = 0;
        std::cin >> count;
        std::println("{}", add_overflows(count, 100));
    }

    Output

    true

    Undefined behaviorThe optimizer trusts you completely

    Optimizers delete checks that could only matter after undefined behavior, assume a pointer you’ve already followed isn’t null, and assume loops with int counters don’t overflow. That’s how they make correct code fast. It’s also why a bug can vanish in a debug build and appear in a release build, or the other way round.

    assert: check your own rules

    Some things must be true if your code is correct: a function’s precondition, such as “the count is never 0 here”. assert(condition), from <cassert>, checks one while the program runs. If it’s false, the program prints the file, line, function and condition, and stops:

    #include <cassert>
    #include <print>
    
    int average_length(int total, int count) {
        assert(count > 0);
        return total / count;
    }
    
    int main() {
        std::println("{}", average_length(600, 4));
        std::println("{}", average_length(600, 0));
    }

    This fails when it runs

    app: main.cpp:5: int average_length(int, int): Assertion `count > 0' failed.

    The program stops at the bug, with the broken rule in the message, instead of dividing by zero later. assert is for bugs in your own code. It’s not for bad input from users or files: the next section shows it can disappear. For those, use the exceptions or std::expected from the two lessons before this one.

    NDEBUG turns asserts off

    If the macro NDEBUG is defined, every assert becomes nothing, so release builds pay nothing for them. The usual way is the flag -DNDEBUG; CMake’s Release build type adds it for you. Here is the same program with that flag: the check is gone, and the division by zero is back, caught by UBSan this time:

    #include <cassert>
    #include <print>
    
    int average_length(int total, int count) {
        assert(count > 0);
        return total / count;
    }
    
    int main() {
        std::println("{}", average_length(600, 4));
        std::println("{}", average_length(600, 0));
    }

    This fails when it runs

    main.cpp:6:18: runtime error: division by zero

    static_assert: check while compiling

    When the condition can be worked out while compiling, static_assert checks it then, and costs nothing when the program runs. It’s ideal for assumptions about sizes and types. Here a file format needs 8-byte records:

    #include <cstdint>
    #include <print>
    
    struct RecordHeader {
        std::uint32_t id;
        std::uint16_t length;
        std::uint16_t flags;
    };
    
    static_assert(sizeof(RecordHeader) == 8, "headers are 8 bytes on disk");
    
    int main() {
        std::println("header: {} bytes", sizeof(RecordHeader));
    }

    Output

    header: 8 bytes

    If the assumption is wrong on some platform, the program doesn’t build there, and the message says why. This code assumes long is 4 bytes, which is true on Windows but not on 64-bit Linux:

    static_assert(sizeof(long) == 4, "the file format needs a 4-byte long");

    The compiler rejects this

    main.cpp: In function ‘int main()’:
    main.cpp:1:28: error: static assertion failed: the file format needs a 4-byte long
        1 | static_assert(sizeof(long) == 4, "the file format needs a 4-byte long");
          |               ~~~~~~~~~~~~~^~~~
    main.cpp:1:28: note: the comparison reduces to ‘(8 == 4)’

    The fix is a type whose size is guaranteed: std::int32_t is exactly 32 bits (4 bytes) on every platform that has it, which is every common one.

    Which one should I use?

    WhatWhenWhyHow
    Warnings as errorsAlways.Catches some undefined behavior before you run: uninitialized variables, returning a local’s address.-Wall -Wextra -Werror
    static_assertAn assumption the compiler can check: sizes, limits, constants.Fails the build, on the platform where it’s wrong; costs nothing at run time.static_assert(sizeof(T) == 8, "…");
    SanitizersEvery debug build and every test run.Catch the common kinds of undefined behavior when they happen, with the line.-fsanitize=address,undefined
    assertRules your own code must keep: preconditions, “can’t happen” cases.Stops at the bug, with the broken rule, in debug builds.assert(count > 0);
    Exceptions or std::expectedBad input from users, files or the network.Must be handled in release builds too.throw … or return std::unexpected(…);

    Rule of thumb: let the compiler and static_assert catch what they can, assert your own rules, run every test with the sanitizers, and handle bad input with real error handling.

    A checklist of habits

    • Build with -Wall -Wextra -Werror and keep the warnings fixed.
    • Run with -fsanitize=address,undefined while you develop and test. Fix the first report, then run again.
    • Give every variable a first value where you declare it.
    • Use std::vector, std::string and smart pointers instead of new and delete.
    • Use .at(), or check the index, when it comes from outside your code.
    • Check for overflow before the arithmetic, or use a wider type.
    • Don’t keep pointers, references or views into a container while it changes.
    • Never rely on what undefined behavior “does” on your machine. It’s allowed to change.

    Under the hood

    Sanitizers work by adding code to your program when it’s compiled. UBSan puts a check before each risky operation: before a signed addition, a check for overflow; before a division, a check for zero. ASan keeps shadow memory: for every 8 bytes of your program’s memory, one shadow byte says how many of them may be used. It surrounds every allocation, on the heap and on the stack, with unusable “red zones”, and keeps freed memory unusable for a while. Each load and store first checks the shadow byte.

    That costs time and memory: a program with ASan typically runs about twice as slowly and uses noticeably more memory. That’s fine for testing, and it’s why release builds leave sanitizers out. ASan also can’t be combined with ThreadSanitizer or MemorySanitizer in one build.

    assert is a macro: a name, like those made with #define, that the preprocessor replaces with code before the compiler sees it. Without NDEBUG, assert(count > 0) becomes a test that, when it fails, calls a library function to print the message and then abort() the program. With NDEBUG, it becomes nothing at all, which is why the expression inside must not do anything the program needs.

    Common pitfalls

    Doing real work inside assert

    An assert whose condition changes something works in a debug build and silently stops working when NDEBUG is defined. Here the count is meant to go up as each read is processed:

    #include <cassert>
    #include <print>
    
    int processed = 0;
    assert(++processed == 1);
    std::println("processed: {}", processed);

    Output

    processed: 0

    Without -DNDEBUG it prints processed: 1. Do the work on its own line, then assert the result: ++processed; assert(processed == 1);.

    Assuming a build without sanitizers proves the code is fine

    A program with undefined behavior often prints the right answer, as add_overflows did at -O0. That proves nothing about the next compiler version, the next optimization level or the next input. If a sanitizer reports something, fix it, even when the output looks right.

    Try it yourself

    Try it yourself

    total_bases multiplies the number of reads by the read length. Add a second call for a real sequencing run, total_bases(20'000'000, 150): as it stands, that overflows an int and UBSan stops the program. Change total_bases to return a std::int64_t so both calls work, and add an assert that neither argument is negative.

    #include <print>
    
    int total_bases(int reads, int read_length) {
        return reads * read_length;
    }
    
    int main() {
        std::println("{}", total_bases(1000, 150));
    }

    Expected output

    150000
    3000000000
    Show a hint

    Multiply in a 64-bit type: convert one of the ints with static_cast<std::int64_t> before multiplying, and return std::int64_t. Add assert(reads >= 0 && read_length >= 0) at the start.

    Show a solution
    #include <cassert>
    #include <cstdint>
    #include <print>
    
    std::int64_t total_bases(int reads, int read_length) {
        assert(reads >= 0 && read_length >= 0);
        return static_cast<std::int64_t>(reads) * read_length;
    }
    
    int main() {
        std::println("{}", total_bases(1000, 150));
        std::println("{}", total_bases(20'000'000, 150));
    }

    20'000'000 * 150 is 3 billion, more than an int can hold, so the int multiplication overflowed: undefined behavior that UBSan reports. Converting one side to std::int64_t first makes the whole multiplication 64-bit, where 3 billion fits easily. The assert documents the precondition and stops a debug build if a caller breaks it.

    Saved in this browser only.