Null Pointer
Null Pointer Program in C++
BeginnerTopic: Memory Management Programs
C++ Null Pointer Program
This program helps you to learn the fundamental structure and syntax of C++ programming.
#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
A null pointer doesn't point to any valid memory location. In C++11, use nullptr (preferred). Always check if a pointer is null before dereferencing to avoid crashes. Setting pointers to null after deletion is a good practice to prevent dangling pointers. Null pointers are useful for: 1) Initialization, 2) Error handling, 3) End-of-list markers, 4) Optional parameters.
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.