Dereferencing a nullptr in C++

In this tutorial, we will discuss the topic, Dereferencing a nullptr in C++”.

So basically, what actually dereferencing a nullptr means?

Dereferencing a nullptr can be thought of as “going to the address where the pointer is pointing to actually and then access the value stored at that address”.

But imagine if you don’t have any address stored in the pointer then how are you going to get the value?

  • This is a similar case whenever we try to dereference a nullptr in order to obtain the value at that location in the memory.
  • Dereferencing null pointer results in undefined behavior. In most cases, it will crash your application.

Let’s understand this with a code snippet,

#include <iostream>
using namespace std;

int main(void)
 int *var = nullptr; //pointer of type integer that stores "nullptr"

 cout << "var -> ";
 cout << *var;
cout << "This will not print";

return 0;

So the output for the above code will be,

var ->
  • After printing out var ->, your program will get crashed.
  • Here you will notice one thing, that your compiler will not show you any warning regarding dereferencing a nullptr. Rather at runtime, there will be a segmentation fault error because of which your application gets crashed.
  • That’s why it is always suggested that you should never dereference nullptr under any circumstances as it leads to undefined results.

Also read:

Leave a Reply