What is a Null Pointer?
A Null Pointer is a pointer that does not point to any memory location. It stores the base address of the segment. The null pointer basically stores the Null value while void is the type of the pointer.
A null pointer is a special reserved value which is defined in a stddef header file. Here, Null means that the pointer is referring to the 0th memory location.
If we do not have any address which is to be assigned to the pointer, then it is known as a null pointer. When a NULL value is assigned to the pointer, then it is considered as a Null pointer.
Applications of Null Pointer
Following are the applications of a Null pointer:
Examples of Null Pointer
int *ptr=(int *)0;
Let's look at the situations where we need to use the null pointer.
In the above code, we declare the pointer variable *ptr, but it does not contain the address of any variable. The dereferencing of the uninitialized pointer variable will show the compile-time error as it does not point any variable. According to the stack memory concept, the local variables of a function are stored in the stack, and if the variable does not contain any value, then it shows the garbage value. The above program shows some unpredictable results and causes the program to crash. Therefore, we can say that keeping an uninitialized pointer in a program can cause serious harm to the computer.
How to avoid the above situation?
We can avoid the above situation by using the Null pointer. A null pointer is a pointer pointing to the 0th memory location, which is a reserved memory and cannot be dereferenced.
In the above code, we create a pointer *ptr and assigns a NULL value to the pointer, which means that it does not point any variable. After creating a pointer variable, we add the condition in which we check whether the value of a pointer is null or not.
In the above code, we use the library function, i.e., malloc(). As we know, that malloc() function allocates the memory; if malloc() function is not able to allocate the memory, then it returns the NULL pointer. Therefore, it is necessary to add the condition which will check whether the value of a pointer is null or not, if the value of a pointer is not null means that the memory is allocated.
Note: It is always a good practice that we assign a Null value to the pointer when we do not know the exact address of memory.