Undefined behaviour: common examples and how to avoid it

Difficulty: Advanced

Question

What is undefined behaviour in C++? Give common examples, explain why it's dangerous, and describe how to detect and avoid it.

Answer

Undefined behaviour, or UB, is where C++ interviews get philosophical, and a strong answer shows you understand the contract between programmer and compiler. Let's cover it properly.

The C++ standard classifies behaviour into a few buckets. Implementation-defined behaviour means the compiler must document what it does (the size of int). Unspecified behaviour means it picks from valid options without documenting (the order in which function arguments are evaluated). Undefined behaviour means the standard places no requirements at all: the program may crash, print garbage, appear to work, or, most subtly, be compiled into something that looks nothing like your source. Compilers assume UB never happens, and use that assumption to optimise. So if a code path would trigger UB, the optimiser may delete checks or the code itself. It is like a contract where you promised never to do X; if you do X, the other party is no longer bound by anything.

Common examples worth naming. Out-of-bounds array or vector access with operator[]. Dereferencing a null or dangling pointer, including use-after-free and returning the address of a local. Signed integer overflow: INT_MAX + 1 is UB for signed types (unsigned overflow wraps and is well defined). This has real consequences: a check like 'if (x + 1 < x)' can be optimised away entirely. Reading an uninitialised local variable. Double delete, and mismatching new[] with delete. Modifying a string literal or a const object. Violating strict aliasing, for example reading a float through an int pointer (use memcpy or std::bit_cast). Data races on non-atomic variables. Shifting by a negative amount or by at least the bit width. Dividing by zero for integers. Modifying a variable twice between sequence points, as in i = i++ + ++i, which is still undefined. Calling a pure virtual function from a constructor. Deleting a derived object through a base pointer without a virtual destructor.

Why is it especially dangerous? Because the symptoms are unreliable. The code may pass every test in debug mode and fail only with -O2, on another compiler, or on a customer's machine. That is what security exploits feed on: many buffer overflow and use-after-free vulnerabilities are UB.

How do you fight it? Use tools: compile with -Wall -Wextra and treat warnings seriously; run under AddressSanitizer (-fsanitize=address) for memory errors, UndefinedBehaviorSanitizer (-fsanitize=undefined) for overflow, shifts, null and misalignment, and ThreadSanitizer for races; use Valgrind; and static analysers like clang-tidy. In code, prefer safer abstractions: std::vector::at() or bounds-checked access in debug builds, std::span, std::array, smart pointers, std::optional instead of null, and checked arithmetic (test for overflow before adding, or use unsigned or wider types). Initialise everything.

A crisp closing line for the interview: 'UB is not just a bug, it removes all guarantees, and the compiler is allowed to assume it never happens.'

Code examples

Safe alternatives to common UB

#include <climits>
#include <iostream>
#include <stdexcept>
#include <vector>

// Checks BEFORE adding; INT_MAX + 1 would be undefined behaviour.
bool safeAdd(int a, int b, int& out) {
    if ((b > 0 && a > INT_MAX - b) || (b < 0 && a < INT_MIN - b)) return false;
    out = a + b;
    return true;
}

int main() {
    std::vector<int> v{1, 2, 3};
    // v[5] would be UB (no bounds check). at() throws instead.
    try {
        std::cout << v.at(5) << "\n";
    } catch (const std::out_of_range&) {
        std::cout << "caught out_of_range\n";
    }

    int r = 0;
    std::cout << safeAdd(INT_MAX, 1, r) << " " << safeAdd(2, 3, r) << " " << r << "\n";

    unsigned u = 0u;
    --u;                          // unsigned wraparound is well defined
    std::cout << (u == UINT_MAX) << "\n";
}

at() turns out-of-bounds into a defined exception. The manual overflow check avoids signed overflow. Unsigned arithmetic wraps by definition.

Key points

Common follow-up questions

Interview tips

Concepts covered

undefined behaviour, signed overflow, out-of-bounds, sanitizers

More C++ & STL questions