A NULL pointer points to memory that doesn't exist. This may be address 0x00000000 or any other implementation-defined value (as long as it can never be a real address). Dereferencing it means trying to access whatever is pointed to by the pointer. The * operator is the dereferencing operator:

Copyint a, b, c; // some integers
int *pi;     // a pointer to an integer

a = 5;
pi = &a; // pi points to a
b = *pi; // b is now 5
pi = NULL;
c = *pi; // this is a NULL pointer dereference

This is exactly the same thing as a NullReferenceException in C#, except that pointers in C can point to any data object, even elements inside an array.

Answer from Greg Hewgill on Stack Overflow
Top answer
1 of 8
118

A NULL pointer points to memory that doesn't exist. This may be address 0x00000000 or any other implementation-defined value (as long as it can never be a real address). Dereferencing it means trying to access whatever is pointed to by the pointer. The * operator is the dereferencing operator:

Copyint a, b, c; // some integers
int *pi;     // a pointer to an integer

a = 5;
pi = &a; // pi points to a
b = *pi; // b is now 5
pi = NULL;
c = *pi; // this is a NULL pointer dereference

This is exactly the same thing as a NullReferenceException in C#, except that pointers in C can point to any data object, even elements inside an array.

2 of 8
56

Dereferencing just means accessing the memory value at a given address. So when you have a pointer to something, to dereference the pointer means to read or write the data that the pointer points to.

In C, the unary * operator is the dereferencing operator. If x is a pointer, then *x is what x points to. The unary & operator is the address-of operator. If x is anything, then &x is the address at which x is stored in memory. The * and & operators are inverses of each other: if x is any data, and y is any pointer, then these equations are always true:

Copy*(&x) == x
&(*y) == y

A null pointer is a pointer that does not point to any valid data (but it is not the only such pointer). The C standard says that it is undefined behavior to dereference a null pointer. This means that absolutely anything could happen: the program could crash, it could continue working silently, or it could erase your hard drive (although that's rather unlikely).

In most implementations, you will get a "segmentation fault" or "access violation" if you try to do so, which will almost always result in your program being terminated by the operating system. Here's one way a null pointer could be dereferenced:

Copyint *x = NULL;  // x is a null pointer
int y = *x;     // CRASH: dereference x, trying to read it
*x = 0;         // CRASH: dereference x, trying to write it

And yes, dereferencing a null pointer is pretty much exactly like a NullReferenceException in C# (or a NullPointerException in Java), except that the langauge standard is a little more helpful here. In C#, dereferencing a null reference has well-defined behavior: it always throws a NullReferenceException. There's no way that your program could continue working silently or erase your hard drive like in C (unless there's a bug in the language runtime, but again that's incredibly unlikely as well).

🌐
Quora
quora.com › What-happens-if-you-dereference-a-null-pointer
What happens if you dereference a null pointer? - Quora
Answer (1 of 8): The outcome is exactly the same as with any other pointer. If the address represents a valid mapping for which the attempted action is permitted (typically read, write or execute, as determined by the instruction that attempts the access and/or its context), the address is resol...
Discussions

What happens when dereferencing a nullptr?
Dereferencing a null pointer is undefined behavior. In practice, trying to dereference null usually results in a seg-fault, but sometimes the compiler can optimize out the operation entirely. In your example, *p == true; doesn't actually change any of the program state, so the compiler is being smart and removing the extra computation. In the cout line, your program is actually using the result of the computation so it can't be removed. Note: In some cases an aggressive optimizer may recognize that dereferencing a null pointer would be undefined behavior and assume that the pointer therefore cannot be null. This can lead to some unintuitive and hard to find bugs. More on reddit.com
🌐 r/cpp_questions
20
14
August 18, 2022
You're dereferencing a null pointer!
If I could up vote this twice or more I would More on reddit.com
🌐 r/ProgrammerHumor
18
628
July 2, 2017
In C++, does dereferencing a nullptr itself cause undefined behaviour, or is it the acting upon the dereferenced pointer which is undefined? - Software Engineering Stack Exchange
But if you don't ask and understand ... they're too dumb to realize that the importance of the question outweighs their dislike of answering it fully. ... It is not the compiler that causes your program to crash on dereferencing a null pointer.... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
August 3, 2021
You're dereferencing a null pointer!
Dereferencing a null pointer does indeed deserve a whack to the back of the head. More on reddit.com
🌐 r/videos
229
4886
July 1, 2017

A NULL pointer points to memory that doesn't exist. This may be address 0x00000000 or any other implementation-defined value (as long as it can never be a real address). Dereferencing it means trying to access whatever is pointed to by the pointer. The * operator is the dereferencing operator:

Copyint a, b, c; // some integers
int *pi;     // a pointer to an integer

a = 5;
pi = &a; // pi points to a
b = *pi; // b is now 5
pi = NULL;
c = *pi; // this is a NULL pointer dereference

This is exactly the same thing as a NullReferenceException in C#, except that pointers in C can point to any data object, even elements inside an array.

Answer from Greg Hewgill on Stack Overflow
🌐
Medium
medium.com › @chanibonner › a-beginners-guide-to-null-pointer-dereference-attacks-d3618cc8a493
A Beginner’s Guide to Null Pointer Dereference Attacks | by Chani Bonner | Medium
February 25, 2024 - If a customer is given a key without a room number on it, she’s going to be really upset. That’s what happens when a pointer has a null value. Let’s see what happens next. Now that you have an idea of what a NPD is, imagine for a minute someone tries to dereference a null pointer in the same way they would a pointer that contains a valid memory address.
🌐
Wikipedia
en.wikipedia.org › wiki › Null_pointer
Null pointer - Wikipedia
2 days ago - The C standard does not say that the null pointer is the same as the pointer to memory address 0, though that may be the case in practice. Dereferencing a null pointer is undefined behavior in C, and a conforming implementation is allowed to assume that any pointer that is dereferenced is not null.
🌐
8th Light
8thlight.com › home › insights › dereferencing null pointer, without a seg fault
8th Light | Dereferencing NULL Pointer, without a Seg Fault
March 5, 2024 - There are no instance variables being used in that function, so it never really goes to read or write to memory at address 0. And since we're not touching that memory, the OS allows us to continue as if we never did anything wrong. And this is how we can pretend to be tough like Chuck Norris, deference NULL (0) pointers, and still get away with it. Now, by no means am I advocating that you write programs like this.
🌐
Mayhem Security
mayhem.security › blog › what-is-null-pointer-dereference
What Is Null Pointer Dereference? | Mayhem
June 1, 2022 - CWE-476 Null Pointer Dereference is a programming error that can occur when a program attempts to deference a null pointer. This can happen when the programmer mistakenly assumes that a pointer pointing to NULL is actually pointing to a valid object.
Find elsewhere
🌐
Reddit
reddit.com › r/cpp_questions › what happens when dereferencing a nullptr?
r/cpp_questions on Reddit: What happens when dereferencing a nullptr?
August 18, 2022 -

I saw this code in A Tour of C++, but with a bit modify for illustration:

#include <iostream>

int main() {
  char s = 'a';
  char *p = &s;
  while (*p) {
    std::cout << *p;
    p++;
  }
  p = nullptr;
  //std::cout << (*p == true);
  *p == true;
}

I do not know how does while (*p) { end while I do not know what happens when p is nullptr. And std::cout << (*p == true) will induce segment fault but *p == true does not.

Top answer
1 of 5
3

It is not the compiler that causes your program to crash on dereferencing a null pointer. The problem is that the pointer is pointing to memory that it is illegal to reference, and the operating system kills your program for invalid behavior.

Trying to trick the compiler by obfuscating that it is a null pointer won't work, because it isn't the compiler that detects it.

There is no legitimate reason to dereference a null pointer unless you on a rare system that maps page zero (or you intend your program to crash). It is generally accepted that zeroing a pointer is a good way to mark it as invalid and dereferencing an invalid pointer is a bug. Modern operating systems do not give you a page of memory at that address specifically to make debugging invalid pointers easier.

I would not even call your program crashing from this to be undefined behavior. Dereferencing a pointer with random data in it would give you undefined behavior. Dereferencing a pointer that contains an address not assigned to your program is quite well defined in demand paged memory protected operating systems, and the behavior defined by the operating system is for your program to crash. From the language's perspective, it is still undefined behavior, because what happens is not defined in the scope of the language. Since this behavior is undefined by the language, the compiler can do nothing about it and should do nothing about it.

The exception to this is systems that have no memory protection and systems that intentionally map page zero. Some older systems do this, but most of the modern systems that do are microcontrollers, some of which might even have memory mapped I/O or some other special purpose memory in page zero.

Since null pointer dereferences are typically bugs, it is unlikely a compiler would bother to optimize away null pointer dereferences or put guard code around a possible one, as this would not improve code performance. If they did even bother to detect this, they would do it to emit a warning to assist you in debugging, similar to the "code not reachable" warning. The only reason for the compiler to generate different code around one would be if it knew what you were trying to do.

2 of 5
9

You seem to have a misunderstanding of what Undefined Behavior means.

Undefined Behavior is not something that is "caused" by your code. It is not something that happens. It is something that is.

If you have some piece of code somewhere that dereferences a null pointer, that is Undefined Behavior. UB gives the compiler a lot of leeway.

The way this is usually phrased is that the compiler is allowed to do anything. It is allowed to compile code that dereferences a null pointer into code that formats your hard disk. It is allowed to compile it into code that crashes. It is allowed to compile it into code that does random things. It is even allowed to compile it into code that doesn't crash.

And until a couple of years ago, that's mostly what compilers did. However, that isn't even the most dangerous part.

There is one thing the compiler is also allowed to do: because you are not allowed to write code that exhibits UB, the compiler is allowed to assume that there will be no UB, when optimizing your code. And because of the complex optimizations that modern compilers do, this can have very weird consequences.

Let's say you have an if (userId == 0) statement, where you have UB in the else part. Since you are not allowed to write code that exhibits UB, the compiler is allowed to assume that the else branch will never be taken. This means that the compiler is allowed to assume that userId will always be 0, i.e. it is allowed to assume that the user is always root! And based on this assumption, it is allowed to optimize away other checks as well, opening you up to huge security holes.

This can lead to very extreme, or even worse, very subtle changes to the behavior of program parts far away from the place of the UB.

🌐
Reddit
reddit.com › r/videos › you're dereferencing a null pointer!
r/videos on Reddit: You're dereferencing a null pointer!
July 1, 2017 - So if I dereferenced the pointer ... be 3. Dereferencing a null pointer means you are dereferencing a pointer that was never assigned a valid memory address which will cause an error....
🌐
Snyk Learn
learn.snyk.io › home › security education › what is a null dereference? | tutorial & examples
What is a null dereference? | Tutorial & examples | Snyk Learn
August 15, 2024 - What you just witnessed is a classic example of a null pointer dereference vulnerability. The extension back-end, specifically the review code, did not check the value of a pointer before dereferencing it.
🌐
Microsoft Learn
learn.microsoft.com › en-us › answers › questions › 433166 › dereferencing-null-pointer-in-c-visual-studio-2019
Dereferencing NULL pointer in C - Visual Studio 2019 - Microsoft Q&A
June 11, 2021 - If you replace the initialization of dArray with malloc, I wonder if the compiler would complain about dereferencing an indeterminate value. ... the key word is "potentially". If calloc should fail then the pointer will be NULL, if it succeeds it won't be NULL.
🌐
Omi AI
omi.me › blogs › firmware-guides › how-to-fix-null-pointer-dereferencing-step-by-step-guide
How to Fix Null Pointer Dereferencing: Step-by-Step Guide – Omi AI
October 25, 2024 - Learn to fix null pointer dereferencing in C with our step-by-step guide. Enhance firmware stability and prevent crashes efficiently with practical solutions. Omi summarizes your meetings, creates tasks and reminders.
🌐
Cplusplus
cplusplus.com › forum › beginner › 71010
Dereferencing Null Pointer - C++ Forum
Any pointer that isn't assigned an address is automatically a nullpointer (or at least some type of bad pointer you shouldn't be dereferencing). You should check that every pointer gets assigned an actual address (new, copy from other pointer, &operator from other variable, ...). Also, make ...
🌐
MathWorks
mathworks.com › polyspace bug finder › reviewing and reporting results › polyspace bug finder results › defects › static memory defects
Dereference of a null pointer - NULL pointer dereferenced - MATLAB
This defect occurs when you use a pointer with a value of NULL as if it points to a valid memory location. If you dereference the zero address, such as 0x00, Polyspace® considers the null address as equivalent to NULL and raises this defect.
🌐
OWASP Foundation
owasp.org › www-community › vulnerabilities › Null_Dereference
Null Dereference | OWASP Foundation
CWE-476: NULL Pointer Dereference: A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.
🌐
Hacker News
news.ycombinator.com › item
I have a clarification: Dereferencing a null pointer in C++ *doesn’t* reliably c... | Hacker News
June 28, 2022 - For anyone who’s wondering, I’m referencing “UB” here (which is short for Undefined Behavior, but don’t be confused by the English language meaning, it’s a precise technical term in the spec). Skipping the details, there’s a surprising (and growing) amount of situations where ...
🌐
Quora
quora.com › Everyone-says-dereferencing-a-null-pointer-is-really-bad-but-what-will-actually-happen-and-why-Im-especially-interested-in-systems-without-paging-as-a-page-fault-would-probably-occour-if-paging-is-present
Everyone says dereferencing a null pointer is really bad, but what will actually happen, and why? (I'm especially interested in systems without paging, as a page fault would probably occour if paging is present) - Quora
So, it’s hard to make general statements on what dereferencing a null pointer will actually do. Both languages say doing so yields undefined behavior. The standards place no requirements on the implementation’s behavior when the behavior is undefined. If the compiler can prove you’re trying to dereference a null pointer, it can literally do anything.