In this article we will try to understand What is Null Pointer in detail.Let me tell you it is a special type of pointer after considering void pointer, it is important for us to understand what are NULL pointers? So, lets get started.
What is Null Pointer ?
A Null pointer is a pointer that does not point any memory location or in other words we can say that it represents an invalid memory location.
When a NULL Value is assigned to a pointer then pointer is consider as NULL pointer.
Example:
int main( )
{
int *ptr=NULL; //here ptr is a NULL pointer.
return 0;
}
Use of NULL Pointer:
1-It is used to initialize a pointer when that pointer is not assigned any valid memory address yet.
Example
int main( )
{
int *ptr=NULL;
return 0;
}
2- Useful for handling errors when we use malloc( ) function.
Example
int main( )
{
int *ptr;
ptr=(int*)malloc(2*sizeof(int));
if(ptr==NULL)
printf("Memory could not be Allocated");
else
printf("Memory allocated successfully");
return 0;
}
Facts About NULL Pointer:
1-The value of NULL is 0.We can either use NULL or 0, but this 0 is written in context of pointer and is not equivalent to the integer 0.
Example
int main( )
{
int *ptr=NULL;
printf("%d",ptr);
return 0;
}
2- Size of the NULL pointer depends upon the platform is similar to the size of the normal pointers.
Example
int main( )
{
printf("%d",sizeof(NULL));
return 0;
}
Important Points:
- It is good practice to initialize a pointer as NULL
- It is good practice to perform NULL check before dereferencing any pointer to surprice.
