In C++, what does the standard guarantee when code indexes past the end of an array or dereferences a null pointer?
answer
- no requirements at all
- no exception, no guaranteed crash
- one past the end: form, never read
- operator[] versus at()
basics
~10 sNothing: 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 sBoth 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#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
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.
Explain the pointer-arithmetic limits: one past the end may be formed and compared but not dereferenced, and anything further is undefined even unread.
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.
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.