Null pointer in C programming language.

Applications of Null Pointer

i. If the pointer does not point to a valid memory address then it is used to initialize NULL pointer variable.
ii. The NULL pointer is used to perform error handling with pointers before dereferencing the pointers.
iii. NULL pointer is passed as a function argument and return from a function.


Examples of Null Pointer
float *ptr=(float *)0;
int *ptr=(int *)0;
char *ptr=(char *)0;
char *ptr='\0';
double *ptr=(double *)0;
int *ptr=NULL;


Situation where we do need NULL pointer.

When memory address is not assigned to the pointer variable.
#include <stdio.h>
int main()
 {
  int *nptr;
   printf("Address fo nptr: %d", nptr);  // printing the value of ptr.
   printf("Value of nptr: %d", *nptr);  // dereferencing the illegal pointer
   return 0;
 }

we declare the pointer variable *nptr and does not assigned it to the address of any variable. The dereferencing *nptr of the uninitialized pointer variable will show the compile-time error because the nptr pointer variable does not point to any variable. As We know that according to the stack memory concept, the local variables of a function are stored in the stack, and if the variable does not assigned or contain any value, then variable shows the garbage value.
The above program may crash and shows unexpected result. An uninitialized pointer variable in C a program can cause serious harm to the computer.
How to avoid the above situation?
See the solution given below.


Solution for the above situation is NULL pointer. The above situation can be avoided using NULL pointer. A null pointer is a pointer pointing to the 0th memory location, which is a reserved memory and cannot be dereferenced.

#include <stdio.h>
int main()
{
  int *nptr=NULL;
  if(nptr!=NULL)
 {
   printf("value of nptr is : %d",*nptr);
 }
 else
 {
   printf("OOPS! Pointer is invalid!..");
 }
 return 0;
}

In the above given program a pointer *nptr is created and assigned a NULL value , which means that it does not point any variable. After creating a pointer variable, we test the value of a pointer is null or not. i.e if(nptr!=NULL)


use the malloc() function:

#include <stdio.h>
int main()
{
 int *ptr;
  ptr=(int*)malloc(4*sizeof(int));
 if(ptr==NULL)
 {
   printf("Memory is not allocated");
 }
  else
 {
    printf("Memory is allocated");
 }
  return 0;
}
Output:
Memory is allocated.


In the above program the malloc() the library function.The malloc() function allocates the memory dynamically or run time, if malloc() function fails to allocate the memory, then it returns the NULL pointer. Therefore, it is necessary to test the condition which will check whether the value of a pointer is null or not, if the value of a pointer is NULL means the memory is not allocated and not null means that the memory is allocated.


Previous Topic:-->> Types of Pointers in C. || Next topic:-->>Void Pointer in C.