Skip to content
Tutorials Center
My learning

Topics

Lesson 63 of 171 ยท Pointers, References and Memory

Undefined Behavior and Memory Safety

Understand undefined behavior in C++ - what it is, why optimizers exploit it, the common causes like out-of-bounds and use-after-free, and how sanitizers catch them.

Most languages define what happens when you make a mistake: reading past the end of an array throws an exception, and dividing by zero raises an error. C++ often doesn't. For a list of operations the standard says the result is undefined behavior (UB): the language places no requirements at all on what the program does. It may crash, print garbage, appear to work, or do something that seems to contradict your source code. And it may do something different after you change an unrelated line or switch compilers.

This isn't carelessness in the language design. Leaving errors undefined lets compilers generate code without hidden checks and lets optimizers assume your program is correct. The cost is that you are responsible for staying inside the rules. In this lesson you'll learn exactly what UB means, why it's more dangerous than "the program crashes", the mistakes that cause most of it, how sanitizers and hardened libraries catch it, and the habits that keep modern C++ code safe. It builds on Pointers, Dynamic Memory: new and delete and Memory Layout: Stack, Heap and Objects.

Four kinds of "it depends"

The standard uses four distinct terms. Only the last one is truly dangerous.

Term Meaning Example
Implementation-defined Each compiler picks a behavior and documents it sizeof(long), whether char is signed
Unspecified One of several valid behaviors, not documented, may vary The order in which f(a(), b()) evaluates a() and b()
Erroneous (C++26) A bug with a defined, harmless-ish result that tools may diagnose Reading an uninitialized int (from C++26 on)
Undefined No requirements whatsoever Signed overflow, out-of-bounds access, use-after-free

Implementation-defined and unspecified behavior are fine to live with: you just shouldn't rely on one particular outcome. Undefined behavior is a bug, full stop. A program that executes UB has no meaning according to the standard, so "but it printed the right answer" proves nothing.

Why the optimizer makes UB worse

It's tempting to think of UB as "whatever the hardware does". On x86, adding 1 to the largest int wraps to a negative number, so surely INT_MAX + 1 is just negative? Not in C++. Because signed overflow is undefined, the compiler may assume it never happens and simplify your code based on that assumption.

C++ The optimizer assumes signed overflow never happens

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The first function prints true for INT_MAX, even though the hardware addition would wrap to a negative number. The compiler reasoned: "x + 1 > x is true for every x where it is defined, and I may ignore the rest", so it replaced the whole function with return true;. No overflow ever happens at run time; the check simply vanished.

That is the core danger. UB doesn't just produce a wrong value at the moment it happens. The compiler's assumption that it can't happen can remove safety checks, reorder code, or turn loops into infinite ones, sometimes far away from the faulty line. Security bugs have come from exactly this: an overflow check written as if (len + offset < len) that the optimizer deleted.

Unsigned arithmetic, by contrast, is defined to wrap modulo 2โฟ, which is why the last line prints 2147483648. See Integer Types for the full rules.

The usual suspects

A small set of mistakes causes most UB in real programs. Learn to recognize each one.

Out-of-bounds access

Indexing a C array, a std::array, a std::vector or a std::span with [] doesn't check the index. Reading one element past the end reads whatever happens to be in memory there; writing there corrupts other variables, heap bookkeeping or a return address. Buffer overflows of this kind are the classic security hole.

C++
std::vector<int> v{1, 2, 3};
int x = v[3];          // UB: valid indexes are 0..2
for (std::size_t i = 0; i <= v.size(); ++i) {   // BUG: <= runs one step too far
    v[i] = 0;
}

Use-after-free and dangling pointers

A pointer or reference that outlives its object is dangling. Using it is UB, even if the memory still holds the old value (which it often does, making the bug invisible in testing). The common ways to get one:

C++
int* p = new int{5};
delete p;
std::println("{}", *p);          // use-after-free

std::vector<int> v{1, 2, 3};
int& first = v[0];
v.push_back(4);                  // may reallocate the buffer...
std::println("{}", first);       // ...so first may refer to freed memory

std::string_view name = std::string{"temporary"};   // the string dies at the ;
std::println("{}", name);        // dangling view

Returning the address of a local is the most famous version. GCC detects the simple case, warns, and then does something you may not expect.

C++ Returning the address of a local

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The compiler prints warning: address of local variable 'local' returned, and at -O1 and above GCC goes further: since dereferencing that pointer could never be valid, it returns a null pointer instead, so a later *p crashes immediately rather than reading stale stack memory. Another compiler, or the same one with different flags, may return the real (dead) address instead. Both are allowed, because the program has no defined meaning.

In C++23 the reference version of this mistake (int& f() { int local = 42; return local; }) no longer compiles, because a returned local is now treated as an rvalue, and a non-const int& can't bind to one. Returning a const int& to a local still compiles with only a warning, and on our server a program that reads the result crashes with a segmentation fault.

Signed overflow and invalid shifts

As shown above, overflowing a signed integer is UB. So is dividing by zero, computing INT_MIN / -1, and shifting by a negative amount or by at least the bit width (1 << 32 for a 32-bit int).

Uninitialized reads

Reading a local variable of a fundamental type before giving it a value is UB up to C++23. The variable holds whatever bytes were left on the stack, and the optimizer may assume any convenient value.

C++
int total;              // no initializer
for (int x : values) {
    total += x;         // UB: reads an indeterminate value
}

C++26 reclassifies this as erroneous behavior: the variable gets some fixed value chosen by the implementation, and compilers are encouraged to diagnose the read. It's still a bug; the change only limits the damage. The fix is the same in every standard: initialize everything (int total = 0;), as you learned in Variables.

Other classics

  • Dereferencing a null pointer. Always UB, never "a guaranteed crash".
  • Modifying a string literal (char* s = (char*)"hi"; s[0] = 'H';) or any object defined const.
  • Data races: two threads access the same variable without synchronization and at least one writes. See Mutexes and Locks.
  • Falling off the end of a non-void function without return (except main, which returns 0 automatically).
  • Calling delete twice, or mixing new[] with delete.
  • Breaking aliasing rules: reading a float's bytes through an int*. Use std::bit_cast or std::memcpy instead.

Letting the compiler find UB

You have three allies that catch UB with little effort: warnings, constant evaluation and sanitizers.

Warnings. Always build with at least -Wall -Wextra (our editor does). GCC catches many simple cases: uninitialized variables, returning addresses of locals, possibly dangling references and some use-after-free. Treat every warning as a bug report until proven otherwise; many teams add -Werror to make warnings fail the build.

Constant evaluation. Inside a constexpr or consteval evaluation, the compiler is required to reject undefined behavior. That turns it into a precise bug detector for code that can run at compile time. This program fails to compile on purpose: every static_assert below triggers UB during evaluation.

C++ Constant evaluation rejects undefined behavior

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

GCC reports array subscript value '3' is outside the bounds of array 'values', overflow in constant expression and the value of 'x' is not usable in a constant expression, each pointing at the exact line. Delete the three bad assertions and the program compiles. Writing small static_assert tests for your constexpr functions is a cheap way to prove they're UB-free for those inputs; Compile-Time Programming: constexpr and consteval goes further.

Sanitizers. For everything that happens at run time, GCC and Clang ship sanitizers: compiler modes that add checks to the generated code and stop the program with a detailed report at the first error.

Terminal
# AddressSanitizer: out-of-bounds, use-after-free, double free, leaks, stack-use-after-return
g++ -std=c++23 -g -O1 -fsanitize=address -fno-omit-frame-pointer main.cpp -o app

# UndefinedBehaviorSanitizer: signed overflow, bad shifts, null deref, misaligned access, ...
g++ -std=c++23 -g -O1 -fsanitize=undefined main.cpp -o app

# Both at once is common in test builds
g++ -std=c++23 -g -O1 -fsanitize=address,undefined main.cpp -o app

# ThreadSanitizer finds data races (can't be combined with AddressSanitizer)
g++ -std=c++23 -g -O1 -fsanitize=thread main.cpp -o app

A use-after-free report from AddressSanitizer looks roughly like this (shortened):

TEXT
==4211==ERROR: AddressSanitizer: heap-use-after-free on address 0x502000000010
READ of size 4 at 0x502000000010 thread T0
    #0 in main main.cpp:7
0x502000000010 is located 0 bytes inside of 4-byte region
freed by thread T0 here:
    #0 in operator delete(void*, unsigned long)
    #1 in main main.cpp:6
previously allocated by thread T0 here:
    #0 in operator new(unsigned long)
    #1 in main main.cpp:5

It tells you what went wrong, where the bad read happened, where the memory was freed and where it was allocated. That turns a bug that "only crashes on the customer's machine" into a five-minute fix. Sanitized programs run roughly 2ร— slower and use more memory, so you use them in tests and debugging, not in release builds. Our online editor compiles with fixed flags, so try sanitizers in your own toolchain; Windows users get AddressSanitizer in MSVC with /fsanitize=address.

Run your whole test suite under -fsanitize=address,undefined in continuous integration. Sanitizers only find bugs on code paths that actually execute, so good tests and sanitizers work as a team.

Checked alternatives at run time

When an index or a number comes from outside your program (user input, a file, the network), check it instead of hoping.

Bounds-checked access. at() on std::vector, std::array, std::string and std::deque throws std::out_of_range instead of reading out of bounds.

Hardened standard libraries. Both GCC's libstdc++ and Clang's libc++ have a mode that checks preconditions inside operator[], front(), back(), iterators and more, and stops the program at the first violation. In libstdc++ you enable it with -D_GLIBCXX_ASSERTIONS on the command line, or by defining the macro before any standard header, as below. C++26 standardizes this idea as the "hardened implementation". This program stops on purpose.

C++ A hardened standard library stops out-of-bounds reads

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The program aborts with a message like Assertion '__n < this->size()' failed instead of silently reading memory beyond the buffer. The examples print to stderr because stderr isn't buffered: text sent to stdout can sit in a buffer and be lost when a program aborts. Many projects enable these assertions in debug builds and some ship them in release builds too, since the checks are cheap.

Checked arithmetic. Test the limits before you compute, or use a helper that reports overflow instead of causing it.

C++ Safe alternatives: at(), checked arithmetic and in_range

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

std::in_range<T>(value) (C++20, <utility>) answers "can this integer be converted to T without changing its value?" without any UB or signed/unsigned surprises. The __builtin_*_overflow functions aren't standard C++, but GCC and Clang both provide them; C++26 adds standard versions through <stdckdint.h> (ckd_add, ckd_sub, ckd_mul), which our GCC doesn't offer in C++ mode yet.

Habits that prevent UB

Tools catch bugs; habits stop you writing them. Modern C++ removes most opportunities for UB if you follow a few rules:

  • Initialize every variable at its declaration. Prefer auto x = value; or brace initialization, which can't be left empty by accident.
  • Let owners manage memory. Use containers, std::unique_ptr and std::shared_ptr instead of raw new and delete (Smart Pointers: std::unique_ptr). No manual delete means no double free and far fewer dangling pointers.
  • Prefer range-based for and algorithms to index loops. They can't run off the end.
  • Use at() or explicit checks for indexes that come from outside, and std::span instead of pointer-plus-length pairs (std::span).
  • Don't keep references, pointers, iterators or views across operations that might invalidate them, such as push_back, insert or erase on a vector.
  • Return owning types (std::string, std::vector) from functions that create data, never references or views to locals.
  • Compile with warnings, test with sanitizers, and enable library assertions in debug builds.
  • Keep integer types consistent and check arithmetic on untrusted input.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A program reads past the end of a vector with v[5] but prints the right answer every time you run it. What can you conclude?

    Undefined behavior has no guaranteed outcome, and "appears to work" is one possible outcome. The bug can surface later in a different build or on a different machine.
  2. 2. Why can GCC compile bool f(int x) { return x + 1 > x; } to return true;?

    For every x where x + 1 is defined, the comparison is true. The optimizer is allowed to ignore the overflowing case entirely, so it folds the expression to true.
  3. 3. Which of these is NOT undefined behavior?

    Unsigned arithmetic is defined to wrap around modulo 2 to the power of the bit width, so UINT_MAX + 1 is 0. The other three are classic undefined behavior.
  4. 4. std::vector<int> v{1, 2, 3}; int& r = v[0]; v.push_back(4); std::println("{}", r); What is the problem?

    When a vector grows past its capacity, it moves its elements to a new buffer and frees the old one. References, pointers and iterators into the old buffer become dangling.
  5. 5. Which tool would most directly report a heap-use-after-free together with where the memory was allocated and freed?

    AddressSanitizer tracks every heap block and stops at the first bad access, printing the access location plus the allocation and deallocation stacks. ThreadSanitizer looks for data races instead.

Summary

  • Undefined behavior means the standard places no requirements on the program. "It worked when I ran it" is not evidence of correctness.
  • Implementation-defined and unspecified behavior are acceptable to live with; undefined behavior is always a bug. C++26 adds erroneous behavior for uninitialized reads.
  • Optimizers assume UB never happens, so UB can delete checks and change code far from the faulty line, as x + 1 > x becoming true shows.
  • The common causes: out-of-bounds access, use-after-free and dangling references, signed overflow and bad shifts, uninitialized reads, null dereference, data races, double delete and aliasing violations.
  • Catch UB with warnings (-Wall -Wextra), constant evaluation (constexpr + static_assert), sanitizers (-fsanitize=address,undefined, thread) and hardened libraries (_GLIBCXX_ASSERTIONS).
  • Prevent it with habits: initialize everything, let containers and smart pointers own memory, prefer range-for and algorithms, use at() and checks on untrusted input, and never hold references across invalidating operations.

Next: Object-Oriented Programming in C++, where you'll start organizing code around classes that protect their own data.