c++objectnullundefined-behaviordereference

At what point does dereferencing the null pointer become undefined behavior?


If I don't actually access the dereferenced "object", is dereferencing the null pointer still undefined?

int* p = 0;
int& r = *p;    // undefined?
int* q = &*p;   // undefined?

A slightly more practical example: can I dereference the null pointer to distinguish between overloads?

void foo(Bar&);
void foo(Baz&);

foo(*(Bar*)0);  // undefined?

Okay, the reference examples are definitely undefined behavior according to the standard:

a null reference cannot exist in a well-defined program, because the only way to create such a reference would be to bind it to the "object" obtained by dereferencing a null pointer, which causes undefined behavior.

Unfortunately, the emphasized part is ambiguous. Is it the binding part that causes undefined behavior, or is the dereferencing part sufficient?


Solution

  • Yes it is undefined behavior, because the spec says that an "lvalue designates an object or function" (at clause 3.10) and it says for the *-operator "the result [of dereferencing] is an lvalue referring to the object or function to which the expression points" (at clause 5.3.1).

    That means there is no description for what happens when you dereference a null pointer. It's simply undefined behavior.