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.
NULL Pointer in C++
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.
Contact Us