Null Pointer

Null Pointer Program in C++

BeginnerTopic: Memory Management Programs
Back

C++ Null Pointer Program

This program helps you to learn the fundamental structure and syntax of C++ programming.

Try This Code
#include <iostream>
using namespace std;

int main() {
    int* ptr = nullptr;  // C++11 way (preferred)
    // int* ptr = NULL;  // C way
    // int* ptr = 0;     // Alternative
    
    cout << "Pointer value: " << ptr << endl;
    
    // Check if pointer is null
    if (ptr == nullptr) {
        cout << "Pointer is null (not pointing to anything)" << endl;
    }
    
    // Safe to check before dereferencing
    if (ptr != nullptr) {
        cout << "Value: " << *ptr << endl;
    } else {
        cout << "Cannot dereference null pointer!" << endl;
    }
    
    // Allocate memory
    ptr = new int(42);
    
    if (ptr != nullptr) {
        cout << "\nAfter allocation:" << endl;
        cout << "Pointer value: " << ptr << endl;
        cout << "Value pointed: " << *ptr << endl;
    }
    
    // Deallocate and set to null
    delete ptr;
    ptr = nullptr;  // Good practice: set to null after delete
    
    if (ptr == nullptr) {
        cout << "\nPointer set to null after deletion" << endl;
    }
    
    return 0;
}
Output
Pointer value: 0
Pointer is null (not pointing to anything)
Cannot dereference null pointer!

After allocation:
Pointer value: 0x7f8a5b402670
Value pointed: 42

Pointer set to null after deletion

Understanding Null Pointer

This program teaches you how to use Null Pointers in C++. A null pointer doesn't point to any valid memory location. It's essential for safe pointer handling, preventing crashes, and indicating that a pointer doesn't currently point to anything.

---

1. What This Program Does

The program demonstrates null pointer usage:

Initializing pointers to nullptr
Checking if pointer is null before dereferencing
Setting pointer to null after deletion
Safe pointer handling practices

Null pointers prevent undefined behavior and crashes.

---

2. Header File Used

This header provides:

cout for displaying output
cin for taking input from the user

---

#include <iostream>

3. 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)

---

4. 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

---

5. Checking for Null

Before Dereferencing

:

if (ptr != nullptr) {

} else {

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

}

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

How it works

:

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

---

6. 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

---

7. 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

---

8. 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

---

9. 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)

---

10. return 0;

This ends the program successfully.

---

Summary

Null pointer: doesn't point to any valid memory location.
Use nullptr (C++11) - preferred over NULL or 0.
Always check if pointer is null before dereferencing.
Set pointer to null after deletion to prevent dangling pointers.
Essential for safe pointer handling and preventing crashes.
Understanding null pointers prevents undefined behavior.
Useful for initialization, error handling, and optional parameters.

This program is fundamental for learning safe pointer practices, understanding error handling, and preparing for robust memory management in C++ programs.

Let us now understand every line and the components of the above program.

Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.

Practical Learning Notes for Null Pointer

This C++ program is part of the "Memory Management Programs" topic and is designed to help you build real problem-solving confidence, not just memorize syntax. Start by understanding the goal of the program in plain language, then trace the logic line by line with a custom input of your own. Once you can predict the output before running the code, your understanding becomes much stronger.

A reliable practice pattern is to run the original version first, then modify only one condition or variable at a time. Observe how that single change affects control flow and output. This deliberate style helps you understand loops, conditions, and data movement much faster than copying full solutions repeatedly.

For interview preparation, explain this solution in three layers: the high-level approach, the step-by-step execution, and the time-space tradeoff. If you can teach these three layers clearly, you are ready to solve close variations of this problem under time pressure.

Table of Contents