skip to content

Classic UB Sources

Signed overflow, out-of-bounds indexing, null dereference, reading uninitialized memory and unsequenced writes are undefined. Interviewers ask which lines in a snippet are UB.

on this pageshow

explore

questions

6

In C++, what does the standard guarantee when code indexes past the end of an array or dereferences a null pointer?

level: juniorimportance: must knowfreq 75%

answer

  1. no requirements at all
  2. no exception, no guaranteed crash
  3. one past the end: form, never read
  4. operator[] versus at()

basics

~10 s

Nothing: both are undefined behaviour, so the standard imposes no requirements, not even a crash. No standard exception is thrown either; only checked members such as std::vector::at() report a bad index, by throwing std::out_of_range.

solid answer

~40 s

Both are **undefined behaviour**, which the standard defines as behaviour for which it imposes no requirements. Reading `a[4]` from `int a[4]`, or `v[5]` from a five-element `std::vector`, is not checked and throws nothing: `operator[]` has the precondition `n < size()` and simply assumes it. The one-past-the-end pointer `a + 4` may be formed and compared but never dereferenced, and `a + 5` is undefined even unread. Dereferencing a null pointer with `*p` or `p->x` is undefined too, and standard C++ has no null-pointer exception. A segfault is a common symptom on desktop systems, not a promise: small overruns usually corrupt neighbouring data silently. For a checked access use `at()`, which throws `std::out_of_range`.

code

cpp · 20 lines
cpp
#include <cstdio>
#include <stdexcept>
#include <vector>

int main() {
    std::vector<int> v{10, 20, 30};
    int* end = v.data() + v.size();   // one past the end: may be formed, never read

    try {
        std::printf("%d\n", v.at(3));  // checked access: throws
    } catch (const std::out_of_range&) {
        std::puts("v.at(3) threw std::out_of_range");
    }
    // v[3] or *end here would be undefined behaviour: no exception, no promised crash.

    int* p = nullptr;
    if (p != nullptr)                  // test before the first dereference
        std::printf("%d\n", *p);
    std::printf("elements: %td\n", end - v.data());
}

go deeper

for a junior

Say plainly that both are undefined behaviour, that operator[] does not check while at() throws std::out_of_range, and that a crash is never guaranteed.

for a middle

Explain the pointer-arithmetic limits: one past the end may be formed and compared but not dereferenced, and anything further is undefined even unread.

for a senior

Show how a silent small overrun corrupts neighbouring state and surfaces far away, and where at(), hardened library modes or range-based loops belong in real code.

for a principal

Frame the trade-off a team sets: unchecked indexing for speed versus checked or hardened access at trust boundaries, and how that policy is enforced.

## What "undefined behaviour" means The C++ standard sorts the behaviour it does not pin down completely into three kinds, and only the third is dangerous in this way: - **Implementation-defined** behaviour is chosen and documented by each implementation, such as the width of `int`. - **Unspecified** behaviour is one of several allowed outcomes, and the implementation need not say which, such as the order in which function arguments are evaluated. - **Undefined behaviour** is, in the standard's own words, behaviour "for which this document imposes no requirements". Once an execution reaches an undefined operation, nothing about that run is promised any more: not a crash, not an exception, not even sensible output from the code around it. Out-of-bounds access and null dereference are the two most familiar members of that third group, and the first two an interviewer reaches for. ## Out-of-bounds access For a built-in array `int a[4]`, the expression `a[i]` means `*(a + i)`, so the rules on pointer arithmetic set the limits: - `a + 0` through `a + 4` are valid pointers. `a + 4` is the **one-past-the-end** pointer: it may be formed, compared and used as a loop bound, which is exactly what `end()` returns for containers, but it must never be read or written through. - `a[4]`, that is `*(a + 4)`, reads an element that does not exist: undefined behaviour. - `a + 5` or `a - 1` is undefined **as soon as it is computed**, even if nothing is ever read through it. The standard containers keep the same contract so that indexing stays free. `std::vector::operator[]`, `std::array::operator[]` and `std::span::operator[]` all have the precondition that the index is less than `size()`. Breaking a precondition is undefined behaviour, and none of these functions is required to check it. The checked access is a separate member: | Access | With a bad index | Run-time cost | |---|---|---| | `a[i]` on a built-in array | undefined behaviour | none | | `v[i]` on `std::vector` or `std::array` | undefined behaviour (precondition) | none | | `v.at(i)` | throws `std::out_of_range` | one comparison | | `*v.end()` | undefined behaviour | none | ## Null pointer dereference The rule for the unary `*` operator is short: if the operand points to an object or function, the result denotes it; otherwise the behaviour is undefined, with a narrow exception for `typeid`. A null pointer points to nothing, so `*p`, `p->field` and `p->method()` with a null `p` are all undefined. C++ has no null-pointer exception: the standard throws nothing, so portable code cannot rely on a `try` block to intercept a null dereference. ## Why "it will just crash" is wrong Desktop operating systems usually leave the page at address zero unmapped, so a null dereference often ends in a segmentation fault or an access violation. That is the platform's reaction on one run, not a guarantee from C++: 1. A small overrun usually lands in memory that **is** mapped, such as another local variable, the next heap block or saved registers, so the program reads garbage or silently corrupts state and fails much later. 2. A large offset from a null pointer, such as a field deep inside a big struct reached through a null struct pointer, can land on a mapped address. 3. On some embedded targets address zero is ordinary memory, so nothing traps at all. 4. Because the standard promises nothing, an optimizing compiler may reason as if the bad access never happens, which can remove the very crash or check you expected; the lesson on optimizer assumptions covers how. ## Writing it defensively - Use `at()` where an index comes from outside the program, such as a file, a packet or user input, and an exception is an acceptable outcome; use `operator[]` in loops whose bounds you control. - Prefer range-based `for` and the standard algorithms, which never form an index at all. - Check a pointer **before** its first dereference, and prefer a reference or `std::optional` where "no object" is not a valid state. - Since C++26 a **hardened implementation** checks many library preconditions, including `operator[]`'s index check, as contract assertions that terminate the program; on a non-hardened implementation the violation remains undefined behaviour. The interview answer fits in one line: out of bounds and through null, C++ promises nothing, so the fix is to make the bad access impossible rather than to rely on what happened when you tried it.

  • Why may a C++ program form the pointer one past the end of an array but not two past it?
    The pointer-arithmetic rules allow results from the first element up to one past the last, so `end()`-style loop bounds and `p != end` comparisons work. Any result outside that range, two past the end or one before the start, is undefined as soon as it is computed, even if it is never dereferenced. The one-past-the-end pointer itself still must not be read or written through.
  • Why doesn't std::vector::operator[] simply check the index on every call?
    C++ keeps the unchecked operation free: a hot loop indexing a vector pays nothing for a check it does not need. The checked operation exists separately as `at()`, which throws `std::out_of_range`. Standard library implementations also offer optional debug or hardened modes, and C++26 standardises hardened implementations that check `operator[]` and terminate, so teams can buy the check where they want it.

Walking past the last numbered room in a hotel corridor: no alarm is guaranteed to sound. Sometimes there is a wall, sometimes you walk into someone else's room and rearrange their furniture without anyone noticing.

  • Reading past the end of an array always crashes with a segmentation fault.
  • std::vector::operator[] throws std::out_of_range when the index is too large.
  • Dereferencing nullptr throws a standard C++ exception, much like a null-pointer exception.
  • Merely forming the one-past-the-end pointer of an array is undefined behaviour.
  • If the out-of-bounds read passed all the tests, it is harmless in production.

Assumes C++23; C++26 adds hardened implementations that turn violated operator[] preconditions into a terminating contract check.

open as a page

In C++, why is INT_MAX + 1 undefined behaviour while UINT_MAX + 1u is well-defined, and did C++20's two's-complement rule change that?

level: middleimportance: must knowfreq 72%

basics

~20 s

Unsigned arithmetic is defined modulo 2^N, so UINT_MAX + 1u is 0. A signed result that does not fit its type is undefined behaviour. C++20 made two's complement mandatory and defined out-of-range conversions, but left signed overflow undefined.

open as a page

In C++17 and later, which of i = i++ + 1, i++ + i++ and f(i++, i++) have undefined behaviour, and why?

level: middleimportance: should knowfreq 55%

basics

~20 s

Only i++ + i++ is undefined: the two operands of + are unsequenced and both modify i. Since C++17, i = i++ + 1 is defined, and f(i++, i++) is only unspecified, because arguments are indeterminately sequenced.

open as a page

In C++, why does a worker thread spinning on while (!done) {} over a plain bool that another thread sets have undefined behaviour?

level: seniorimportance: should knowfreq 50%

basics

~20 s

It breaks two rules. The unsynchronized write and reads of a non-atomic bool are a data race, which is undefined behaviour; and a loop doing no I/O, volatile or atomic access may be assumed to terminate. Use std::atomic<bool>.

open as a page

Reviewing a C++ image decoder that computes int pixels = width * height from header fields, loops for (int i = 0; i <= pixels; ++i), and sets alpha only for one-channel input, which undefined behaviours do you flag?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Signed overflow in width * height and again in pixels * 4, an off-by-one i <= pixels that reads and writes past both buffers, and an uninitialized alpha read. Validate the header, size in std::size_t with pre-checks, initialize alpha.

open as a page

In C++, what happens when a function reads a local int it never initialized, and how does C++26 erroneous behaviour change that?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Up to C++23, reading an uninitialized local int produces an indeterminate value and is undefined behaviour. C++26 gives such locals an erroneous value: reading it is erroneous behaviour, well-defined but diagnosable, unless the variable is marked [[indeterminate]].

open as a page