A NULL Pointer in C++ indicates the absence of a valid memory address in C++. It tells that the pointer is not pointing to any valid memory location In other words, it has the value "NULL" (or 'nullptr' since C++11). This is generally done at the time of variable declaration to check whether the pointer points to some valid memory address or not. It is also returned by several inbuilt functions as a failure response.
Trying to dereference a NULL pointer i.e. trying to access the memory it points to leads to some undefined behavior leading to the program crash.
Syntax of Null Pointer in C++
We can create a NULL pointer of any type by simply assigning the value NULL to the pointer as shown:
int* ptrName = NULL; // before C++11
int* ptrName = nullptr
int* ptrName = 0; // by assigning the value 0
A null pointer is represented by the value 0 or by using the keyword NULL. With the new versions of C++ like C++11 and later, we can use "nullptr" to indicate a null pointer.
Checking NULL Pointer
We can check whether a pointer is a NULL pointer by using the equality comparison operator.
ptrName == NULL
or
ptrName == nullptr
The above expression will return true if the pointer is a NULL pointer. False otherwise.
Applications of Null Pointer in C++
Null Pointer finds its applications in the following scenarios:
- Initialization: It is a good practice to Initialize pointers to a null value as it helps avoid undefined behavior by explicitly indicating they are not pointing to valid memory locations.
- Default Values: Null pointers act as default or initial values for pointers when no valid address is assigned to the pointers.
- Error Handling: They are useful in error conditions or to signify the absence of data that enables better handling of exceptional cases.
- Resource Release: To release the resources, like the destructor of a class, or to set pointers to NULL after deletion we can use a null pointer to avoid accidentally using or accessing the released memory.
- Sentinel Values: A null pointer can be used to indicate the end of a data structure or a list like in the linked list last node has a null pointer as the next field.
Example of NULL Pointer in C++
The below example demonstrates the dereferencing and assignment of a null pointer to another value.
C++
// C++ program to demonstrate the dereferencing and
// assignment of null pointer to another value.
#include <iostream>
using namespace std;
int main()
{
int* ptr = nullptr;
// Checking if the pointer is null before dereferencing
if (ptr == nullptr) {
cout << "Pointer is currently null." << endl;
}
else {
cout << "Pointer is not null." << endl;
}
// *ptr = 10; (to avoid runtime error)
// Assigning a valid memory address to the pointer
int value = 5;
ptr = &value;
// Checking if the pointer is null after assigning a
// valid address
if (ptr == nullptr) {
cout << "Pointer is currently null." << endl;
}
else {
cout << "Pointer is not null." << endl;
cout << "Value at the memory location pointed to "
"by the pointer: "
<< *ptr << endl;
}
return 0;
}
OutputPointer is currently null.
Pointer is not null.
Value at the memory location pointed to by the pointer: 5
Explanation: In the example given above first the pointer is pointing to a null value. First, we check whether the pointer is pointing to a null value or not before dereferencing it to avoid any kind of runtime error. Then we assign the pointer a valid memory address and then check it before dereferencing it. As the pointer is not pointing to a null value, the else part is executed.
Disadvantages of NULL Pointers in C++
NULL pointer makes it possible to check for pointer errors but it also has its limitations:
- Dereferencing a NULL pointer causes undefined behavior that may lead to runtime errors like segmentation faults.
- We need to check explicitly for NULL pointers before dereferencing it to avoid undefined behavior.
Conclusion
It is important to understand null pointers in C++ to handle pointers safely and prevent unexpected runtime errors. They signify the absence of valid memory addresses and help in error handling and pointer initialization. Proper usage and precautions regarding null pointers are essential in writing error-free C++ code.
Similar Reads
C++ Programming Language C++ is a computer programming language developed by Bjarne Stroustrup as an extension of the C language. It is known for is fast speed, low level memory management and is often taught as first programming language. It provides:Hands-on application of different programming concepts.Similar syntax to
5 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Object Oriented Programming in C++ Object Oriented Programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so th
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
Inheritance in C++ The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object-Oriented Programming in C++. In this article, we will learn about inheritance in C++, its modes and types along with the informatio
10 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read