Search code examples
c++pointersundefined-behaviorlanguage-design

Why is dereferencing a null pointer undefined behaviour?


According to ISO C++, dereferencing a null pointer is undefined behaviou. My curiosity is, why? Why has the standard decided to declare it undefined behavior? What is the rationale behind this decision? Compiler dependency? Doesn't seem, because according to C99 standard, as far as I know, it is well defined. Machine dependency? Any ideas?


Solution

  • Defining consistent behavior for dereferencing a NULL pointer would require the compiler to check for NULL pointers before each dereference on most CPU architectures. This is an unacceptable burden for a language that is designed for speed.

    It also only fixes a small part of a larger problem - there are many ways to have an invalid pointer beyond a NULL pointer.