A function that dereferences a pointer and then tests it against NULL, and the same function as the compiler emitted it with the test deleted - because a dereferenced pointer cannot be NULL in a program with no undefined behaviour.

Undefined behaviour is not a crash. It is a promise you made to the compiler

Here is a function with a bug in it. The bug is not where you think.

int get(struct node *p)
{
    int v = p->value;
    if (p == NULL) {
        return -1;
    }
    return v;
}

The obvious reading is that the null check is in the wrong place — it should come first — but that the code is otherwise merely clumsy. Call it with NULL and you get a segmentation fault at the first line. Annoying, findable, fixed in a minute.

That is not what happens. Compile this with optimisations on and the check is not in the binary at all. Not reordered. Not skipped at runtime. Deleted at compile time, along with the return -1 it guarded.

And the compiler is right to do it.

The reasoning, step by step

The C standard says that dereferencing a null pointer is undefined behaviour. What it means by that is narrower and stranger than most people assume: it does not say the program will crash, and it does not say the compiler must detect it. It says the standard imposes no requirements at all on what such a program does.

From that, the compiler draws a conclusion that is entirely logical:

  1. This program dereferences p on the first line.
  2. If p were NULL, that would be undefined behaviour.
  3. The standard imposes no requirements on programs with undefined behaviour, so the compiler is entitled to assume there is none.
  4. Therefore p is not NULL.
  5. Therefore p == NULL is false.
  6. Therefore the if body is unreachable, and dead code can be removed.

Every step follows. There is no bug in the optimiser. The only questionable step is the one you made, by writing a dereference before the check and thereby promising the compiler something that was not true.

This is the thing worth internalising: undefined behaviour is not a runtime event. It is a compile-time assumption. The compiler is not waiting to see whether you pass NULL. It has already concluded that you never will, and it has rewritten your program on that basis.

Why a compiler would do something so unhelpful

It sounds adversarial. It is not — it is the whole reason C is fast.

Consider a loop:

for (int i = 0; i <= n; i++) {
    total += data[i];
}

Signed integer overflow is undefined behaviour in C. So the compiler may assume i never overflows. That assumption lets it conclude the loop terminates, which lets it unroll the loop, vectorise it, hoist the bound out, and keep i in a register across the whole thing. If signed overflow were instead defined to wrap, the compiler would have to consider the possibility that i wraps to a large negative number and the loop runs again — and almost all of that optimisation would become illegal.

The same bargain appears everywhere. Strict aliasing — the rule that an int * and a float * cannot point at the same object — lets the compiler keep a value in a register instead of reloading it after every write through an unrelated pointer. Assuming no out-of-bounds access lets it reorder reads. Assuming no null dereference lets it move a load earlier, before a branch.

C's performance is substantially built from the things the standard declines to define. The cost is that when you break one of those assumptions, you do not get an error. You get a program compiled against a false premise.

It is not the same as unspecified or implementation-defined

Three terms get used interchangeably, and separating them is the first step to reading the standard usefully.

Implementation-defined means the implementation must choose a behaviour and document it. The size of int is implementation-defined: your compiler has an answer, it is written down, and you can rely on it as long as you stay on that compiler.

Unspecified means there are several permitted behaviours and the implementation need not tell you which it picked. The order in which function arguments are evaluated is unspecified — f(g(), h()) may call either first. Your program is still a valid program; you just cannot depend on the order.

Undefined is different in kind. There are no permitted behaviours because there are no requirements. The program is not a valid C program, and the standard explicitly notes that permissible outcomes include ignoring the situation entirely with unpredictable results, and terminating the translation — the compiler is allowed to simply refuse.

A useful way to hold it: with implementation-defined behaviour, the compiler makes a choice and tells you. With unspecified, it makes a choice and does not. With undefined, it was never your program to reason about in the first place.

The ones that actually bite

A short list, because knowing the names means recognising them in your own code.

Signed integer overflow. INT_MAX + 1 is undefined. Unsigned overflow is defined — it wraps, by the standard — which is why bit manipulation and hashing code uses unsigned types. If you need wrapping arithmetic, say unsigned.

Reading uninitialised memory. Not merely "you get a garbage value". The compiler may assume the read never happens and behave accordingly, which is why an uninitialised variable can appear to have two different values in two places in the same function.

Out-of-bounds access. a[i] is defined as *(a + i), with no bounds check anywhere. One past the end is undefined even to form as a pointer in some cases, let alone to dereference.

Use after free. The pointer still holds an address and the memory may still contain your data, right up until the allocator hands that block to somebody else. This is why the habit of setting a pointer to NULL after free is worth the keystrokes: it turns an invisible corruption into an immediate, locatable crash.

Strict aliasing violations. Writing a float and reading it back through an int * is undefined, and the compiler may keep the old value in a register because it is entitled to assume the two pointers cannot refer to the same memory. The portable way to reinterpret bytes is memcpy, which every compiler recognises and compiles away to nothing.

Modifying a variable twice between sequence points. i = i++ and a[i] = i++ have no defined meaning.

Shifting too far. 1u << 32 on a 32-bit unsigned is undefined. Not zero. Undefined.

The part that makes it genuinely difficult

Undefined behaviour does not have to fail. That is the whole problem.

A program with undefined behaviour may work perfectly for years. It may work on your laptop and fail on the build server. It may work at -O0 and break at -O2, because the optimiser only applies the assumption when it has reason to. It may work until you add an unrelated function, because the inliner then exposes the assumption to a caller that does pass NULL.

This is why "it works" is a weak claim about a C program, and why "it stopped working when we turned on optimisations" is almost never an optimiser bug. The usual sequence is: the program always had undefined behaviour, the old compiler did not exploit it, and the new one does. The bug did not appear. It became visible.

It also explains a frustrating conversation that recurs on every C project. Somebody reports that a null check "disappeared", or that a loop "ran forever when it shouldn't have", and files it against the compiler. The compiler is almost always right, and the proof is usually three lines above the reported symptom.

This has happened to real code

The pattern at the top of this article is not a teaching example invented to make a point. It is a Linux kernel vulnerability from 2009.

The network tunnel driver contained, in effect, this shape:

struct sock *sk = tun->sk;      /* dereferenced here */
if (!tun) {
    return POLLERR;             /* checked here */
}

GCC reasoned exactly as described above: tun was dereferenced on the first line, so in a program without undefined behaviour tun cannot be null, so the check is dead, so remove it. The check vanished from the compiled kernel.

On its own that is a null dereference and a crash. What made it a privilege escalation was that on the systems of the day a user could map a page at address zero, so the dereference did not fault — it read attacker-controlled memory and carried on. A missing check plus a mappable zero page is a root exploit.

Nobody wrote that bug by being careless with pointers. It was written by somebody who had put a null check in, and whose check was removed by a compiler doing precisely what the standard permits.

Checking what the compiler actually did

You do not have to take any of this on trust, and looking is a better habit than believing.

gcc -O2 -S -masm=intel get.c -o -

That prints the assembly for the function. In the example at the top, the comparison and the branch are simply absent — there is no test, no cmp, no path that returns -1. For a quicker look, Compiler Explorer does the same thing in a browser and colour-matches source lines to the instructions they produced, which makes a deleted line obvious because nothing highlights.

Doing this once, on your own code, changes how the rest of this reads. There is a difference between knowing that the compiler is allowed to delete your check and seeing the gap where it used to be.

A worthwhile exercise: compile the function from the top of this article at -O0 and again at -O2, and diff the two outputs. At -O0 the check is there, because the optimiser that would remove it is not running. That is also the clearest demonstration of why "it works in a debug build" proves nothing at all.

So what do you actually do about it

Three things, in order of how much they are worth.

Turn on the sanitisers. This is by far the highest-value habit in modern C, and it is one flag:

gcc -fsanitize=address,undefined -g main.c -o main

UBSan catches signed overflow, bad shifts, misaligned access and null dereference at the moment they happen, and prints the file and line. ASan catches buffer overruns, use-after-free and leaks. Between them they turn most of this article from a thing you must hold in your head into a thing your toolchain tells you about. Run your tests under them. The cost is a slower binary during development and nothing at all in release.

Turn on the warnings, and read them. -Wall -Wextra catches a surprising amount statically, including the function at the top of this article — GCC and Clang both warn that the null check is redundant after the dereference. The warning is right there, in the build output, before any of this becomes a mystery.

Learn the list. Not all of it. The seven above cover the overwhelming majority of what appears in real code, and recognising them while writing is cheaper than finding them afterwards.

The mental shift

Most people learn C with a model that goes: the compiler translates my code, and if my code does something invalid, the machine does something unpredictable.

The accurate model is different. The compiler and you have an agreement. You promise your program contains no undefined behaviour. In exchange, the compiler is permitted to use that promise to generate fast code — to assume loops terminate, pointers are valid, arithmetic does not overflow, unrelated pointers do not alias.

Break the promise and the compiler does not catch you out. It simply keeps reasoning from a false premise, and the conclusions it reaches are as sound as the premise was. A null check deleted from a function that dereferences first is not the compiler being clever at your expense. It is the compiler believing you.

Which is also the reason this is worth understanding rather than memorising. You cannot enumerate the consequences of a false premise; new optimisation passes find new consequences every release. What you can do is stop making the promise falsely.

Write the check before the dereference.


Undefined behaviour, pointers and the memory model are phases three and four of C: From Source to Systems, free to read in full.

c undefined behaviour compilers optimisation systems programming