skip to content

In C++, why can the optimizer remove an if (p == nullptr) check that comes after p->length has already been read?

level: seniorimportance: should knowfreq 45%

answer

  1. the dereference is a promise
  2. null dereference is undefined
  3. the later check is provably dead
  4. inlining moves the facts around
  5. check first, then touch

basics

~20 s

Reading p->length is undefined if p is null, so after that read the compiler may assume p is not null and delete the later p == nullptr test as dead code. Put the null check before the first dereference.

solid answer

~40 s

Dereferencing a null pointer is **undefined behaviour**, so a valid execution that reaches `p->length` has a non-null `p`. From that point the optimizer may treat `p != nullptr` as a known fact and delete `if (p == nullptr) return -1;` as unreachable. Apple clang 21 at `-O2` compiles such a function to a single load and a return; with GCC's and Clang's `-fno-delete-null-pointer-checks` it keeps the test. The danger is that the check was the only defence: on a target where address zero is mapped, or where the load is folded away, a null pointer now sails through. Inlining spreads the effect, because a dereference in one function can delete a check in its caller or callee. The fix is ordering: test the pointer before the first access.

code

cpp · 18 lines
cpp
#include <cstdio>

struct Packet {
    int length;
    const unsigned char* payload;
};

// Fixed order: test the pointer before the first dereference.
int payload_length(const Packet* p) {
    if (p == nullptr)
        return -1;
    return p->length;
}

int main() {
    Packet pk{42, nullptr};
    std::printf("%d %d\n", payload_length(&pk), payload_length(nullptr));
}

go deeper

for a junior

Remember the ordering rule: check a pointer for null before the first time you read through it, never after.

for a middle

Explain how a dereference lets the optimizer conclude the pointer is non-null and remove a later check.

for a senior

Show how inlining spreads the effect across functions, why trap-free platforms make it dangerous, and how references and optional remove the question.

for a principal

Decide whether a codebase on unusual targets must build with null-check deletion disabled, and enforce check-before-use in review.

## The shape of the bug The pattern usually appears after a refactor that moved a convenient read above the guard: ```cpp int payload_length(const Packet* p) { int n = p->length; // dereference first... if (p == nullptr) // ...then check return -1; return n; } ``` To a reader the check looks like protection. To the compiler it is a statement about a program that has already ended its defined behaviour. ## Why the compiler may delete it The standard defines the unary `*` operator, and therefore `->`, only when the operand points to an object; otherwise the behaviour is undefined. So there are two cases at the line `int n = p->length;`: 1. `p` is not null: the read is valid, and the later `p == nullptr` is false. 2. `p` is null: the program has undefined behaviour, and nothing is required. As with any optimization based on undefined behaviour, the compiler only has to get case 1 right, and in case 1 the check never fires. Value-range and null-check elimination passes record "`p` was dereferenced, so `p` is non-null" and remove the branch. Apple clang 21 at `-O2` turns `payload_length` into two instructions: load `p->length`, return it. GCC documents the same behaviour for its option `-fdelete-null-pointer-checks`: dataflow passes "eliminate useless checks for null pointers", assuming that if a pointer is checked after it has already been dereferenced, it cannot be null. The documentation says it is enabled by default on most targets and completely disabled on AVR and MSP430, where address zero holds real data. With `-fno-delete-null-pointer-checks`, Apple clang 21 keeps the branch and even moves the load after it. The option tables are the toolchain's material; the point here is that the language allows the deletion. ## Why it matters in practice - **The crash you counted on may not happen.** If the read of `p->length` is itself optimized away because `n` is unused on some path, or if address zero is mapped, a null `p` reaches code that trusted the check. - **The effect crosses function boundaries.** After inlining, a dereference in a small helper such as `size(p)` can delete a null check in the caller that follows it, even though the two lines sit in different files. - **Kernels and firmware are exposed.** Code running where page zero can be mapped, or where address zero is a valid register or vector table, cannot rely on a trap, which is why such projects often build with the option that keeps the checks. ## Writing the guard so it survives 1. **Check before the first access.** Move every read through the pointer below the test, including reads hidden in initializers and in arguments to logging calls. 2. **Prefer references** for parameters that must not be null; a reference cannot be bound to "no object" in a valid program, so the question disappears from the signature. 3. **Use `std::optional`** or a status return for "may be absent", so that absence is a value rather than a null pointer. 4. **Assert the precondition** at the top of the function in debug builds so violations are caught where they enter. ## Related cases | Pattern | What the optimizer may conclude | |---|---| | `p->x` then `if (!p)` | the check is dead | | `memcpy(dst, p, n)` then `if (!p)` | `memcpy` requires valid pointers, so the check may be dead | | `int v = arr[i];` then `if (i >= size)` | out-of-bounds access is undefined; the bound check may be treated as dead when the compiler can see the array | | `this->member` then `if (this == nullptr)` | `this` is never null in a valid member call; the check is dead | The last row is a classic from older codebases that called member functions through null pointers "safely"; modern compilers delete such checks routinely. ## Spotting it in review - Look for **initializers and logging** that read through the pointer above the guard, such as `auto n = p->size();` or a trace line that prints `p->id`. - Look for **helpers called before the guard** that dereference internally; after inlining they count as a dereference in the caller. - Treat a null check **after** any use as a finding even when the code has "always worked": the generated code may already lack the check. - Keep null-dereference diagnostics enabled in optimized builds: GCC documents that its `-Wnull-dereference` is only active when null-check deletion is, and that its precision depends on the optimization options.

  • Can a dereference in an inlined helper delete a null check in its caller?
    Yes. Once `size(p)` is inlined into the caller, the caller's code contains the dereference, and any `if (p == nullptr)` that comes after it in the same flow becomes dead by the same reasoning. The check and the dereference may sit in different source files; inlining puts them side by side for the optimizer.
  • Why do some firmware and kernel builds disable the null-check deletion?
    Their platforms may map memory at address zero, or keep a vector table or registers there, so a null dereference does not trap and the compiler's assumption that a checked-after-use pointer cannot be null is unsafe. GCC documents that its option is disabled entirely on AVR and MSP430; other projects pass `-fno-delete-null-pointer-checks` explicitly.

  • A null check anywhere in the function protects every dereference in it.
  • A null dereference always traps, so a later check never matters.
  • The compiler only deletes the check when it can prove p is non-null from the caller.
  • Checking this == nullptr inside a member function is a valid safety net.