Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Null Pointer in C++

Use nullptr in C++ to mark a pointer that points nowhere, check it before dereferencing, and reset it after delete. Covers NULL vs nullptr and bad_alloc.

BeginnerMemory Management ProgramsExample 6 of 11
null-pointer.cpp
1#include <iostream>
2using namespace std;
3
4int main() {
5 int* ptr = nullptr; // C++11 way (preferred)
6 // int* ptr = NULL; // C way
7 // int* ptr = 0; // Alternative
8
9 cout << "Pointer value: " << ptr << endl;
10
11 // Check if pointer is null
12 if (ptr == nullptr) {
13 cout << "Pointer is null (not pointing to anything)" << endl;
14 }
15
16 // Safe to check before dereferencing
17 if (ptr != nullptr) {
18 cout << "Value: " << *ptr << endl;
19 } else {
20 cout << "Cannot dereference null pointer!" << endl;
21 }
22
23 // Allocate memory
24 ptr = new int(42);
25
26 if (ptr != nullptr) {
27 cout << "\nAfter allocation:" << endl;
28 cout << "Pointer value: " << ptr << endl;
29 cout << "Value pointed: " << *ptr << endl;
30 }
31
32 // Deallocate and set to null
33 delete ptr;
34 ptr = nullptr; // Good practice: set to null after delete
35
36 if (ptr == nullptr) {
37 cout << "\nPointer set to null after deletion" << endl;
38 }
39
40 return 0;
41}

Sample Output

Cannot dereference null pointer!

The null check prevented a crash.

Value pointed: 42

After new int(42).

In this one

  • How to initialize and test a pointer with nullptr
  • Why dereferencing null is undefined behavior
  • Why resetting to nullptr after delete is a habit, not a guarantee
  • Why nullptr is better than NULL or 0

How it works

  1. 1

    ptr starts as nullptr and prints as 0.

  2. 2

    Both checks see it is null and skip the dereference.

  3. 3

    new int(42) gives ptr a real address.

  4. 4

    delete frees it; ptr = nullptr resets it.

Edge cases

Dereferencing null

Print *ptr while it is nullptr.

Undefined behavior, typically a segmentation fault.

Copy of a deleted pointer

int* q = ptr; delete ptr; ptr = nullptr;

q still holds the old address and is dangling. Setting one pointer to null does not fix its copies.

What's going on

A null pointer is a pointer that deliberately points at nothing. In modern C++ you write it as nullptr. Checking for it before dereferencing is how you avoid crashes.

int* ptr = nullptr; starts the pointer in a known "empty" state instead of holding garbage.

Printing it shows "Pointer value: 0" in the sample. The exact text depends on the standard library: libstdc++ (GCC) prints 0, libc++ (Clang on macOS) prints 0x0.

if (ptr == nullptr) is the check. The second if shows the safe pattern: dereference only in the branch where the pointer is not null. *ptr on a null pointer is undefined behavior; on most systems it crashes with a segmentation fault.

ptr = new int(42); allocates an int on the heap and stores its address. Note that a plain new never returns null when it fails; it throws std::bad_alloc. So the if (ptr != nullptr) after new is defensive but will always be true here.

delete ptr; frees the memory. The pointer still holds the old address afterwards; nothing clears it for you. Using it now would be undefined behavior. ptr = nullptr; is a habit that makes later checks honest and turns an accidental second delete into a harmless no-op. It does not protect other pointers that copied the same address.

Older code uses NULL or 0. nullptr is better because it has a real pointer type, so it cannot be confused with the integer 0 in overloaded function calls.

The only header is <iostream>. It gives you cout for displaying output and cin for taking input from the user.

Understanding Null Pointers

Null Pointer Concept:

Pointer that doesn't point to any valid memory
Indicates "no object" or "not initialized"
Safe to check but not to dereference
Essential for safe pointer handling

C++11 Way:

int* ptr = nullptr; // Preferred

Legacy Ways:

int* ptr = NULL; // C way (macro)

int* ptr = 0; // Alternative (not recommended)

Initializing to Null

Safe Initialization:

int* ptr = nullptr; // Initialize to null

Why?

Prevents uninitialized pointer
Can safely check if (ptr == nullptr)
Prevents accidental dereferencing
Good programming practice

Checking for Null

Before Dereferencing:

if (ptr != nullptr) {

cout << *ptr << endl; // Safe to dereference

} else {

cout << "Pointer is null!" << endl;

}

What happens here:

Always check before dereferencing
Prevents crashes from null pointer dereference
Essential safety check

Setting to Null After Deletion

Good Practice:

delete ptr;

ptr = nullptr; // Set to null after deletion

Why?

Prevents dangling pointer
Can check if pointer was deleted
Prevents double deletion
Makes code safer

When to Use Null Pointers

Best For:

Pointer initialization
Error handling (function returns null on error)
End-of-list markers (linked lists)
Optional parameters
Conditional object creation

Example Scenarios:

Function returns null if allocation fails
Linked list: null indicates end
Optional function parameters
Conditional object pointers

Null Pointer Dereference

Danger:

int* ptr = nullptr;

*ptr = 10; // CRASH! Undefined behavior

Why Crashes?

Tries to access invalid memory
Operating system prevents access
Program crashes or undefined behavior
Always check before dereferencing

Important Considerations

nullptr vs NULL vs 0:

nullptr: C++11, type-safe, preferred
NULL: C macro, less type-safe
0: Works but not recommended

Type Safety:

nullptr is type-safe
Cannot be confused with integer 0
Better compiler error messages

Best Practices:

Always initialize pointers
Check for null before dereferencing
Set to null after deletion
Use nullptr (not NULL or 0)

return 0;

This ends the program successfully.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What does delete ptr; do to the value stored in ptr?

Pick an answer to check it.

Question 2

Why prefer nullptr over NULL?

Pick an answer to check it.

Questions people ask

Does new return nullptr on failure?

No, it throws std::bad_alloc. new (nothrow) int returns nullptr instead.

Is delete nullptr safe?

Yes, it does nothing.

Why does my output show 0x0?

Some standard libraries print null pointers that way.