Profile photo for Robert Love

I dislike answering these sorts of questions as there are so many different answers and the question is underspecified. As Tim Wilson noted, the correct answer is "that is undefined." Full stop.

Nonetheless, I was asked to answer this, so I'll discuss what actually happens on a modern system such as Linux. I think the underlying mechanics are what you are trying to get at.

First, some preliminaries: NULL is numerically zero. That is, NULL == 0 is always true. C and C++ allow, however, NULL's internal representation to differ from zero as dictated by a specific implementation. It is up to the compiler then to translate zero to the proper internal representation and vice versa.

For the rest of this answer, we'll assume NULL's internal representation and its numerical representation are both zero. That is true on nearly any system you will ever work on, including Linux/x86.

So to your question: What actually happens when you dereference NULL? I'll repeat the previous caveat: Doing so is undefined, which means literally anything can happen. Undefined doesn't mean "crash" and it doesn't mean (as many people think) "implementation specific." It means anything—and maybe something different every time—can happen.

Nonetheless, the behavior on Linux is rather consistent: Segfault. How that happens is both simple and elegant:

  1. The page starting at virtual address 0x0 is mapped into every user-space process on Linux with no access permissions (by mapping it, the kernel ensures nothing else will ever be mapped there).
  2. Linux compilers treat the internal representation of NULL as zero and happily let you dereference the pointer.
  3. The page fault handler is invoked as the page at 0x0 is not resident.
  4. The page fault handler notices your operation isn't allowed (as none are).
  5. The page fault handler fails, refusing to fault in the page.
  6. The kernel sends the process a SIGSEGV, for which the default behavior is process termination plus core generation. In other words, you crash.


Thus, without any special compiler or kernel support except a page mapped at
0x0, Linux provides the expected behavior for a NULL dereference.

View 9 other answers to this question
About · Careers · Privacy · Terms · Contact · Languages · Your Ad Choices · Press ·
© Quora, Inc. 2025