NULL Pointer in C

NULL Pointer in C

In this tutorial, you are going to learn about NULL Pointer in C, use of Null pointers, facts related to Null pointer and best practices related to Null pointers.

NULL Pointer in C

A NULL pointer is a pointer that does not point to any memory location. It represents an invalid memory location. When a NULL value is assigned to a pointer, then the pointer is considered as NULL pointer.

Example:

int main
{
    int *ptr= NULL;
return 0;
}

Use of NULL Pointer

  1. It is used to initialize a pointer when that pointer isn't assigned any valid memory address yet.
  2. Useful for handling errors when using 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 pointers and is not equivalent to the integer 0.

Example:

  int main()
{
  int *ptr= NULL;
printf("%d", ptr);
return 0;
}

 OUTPUT: 0

2. Size of the NULL pointer depends upon the platform and is similar to the size of the normal pointers.

Example:

int main()
{
  printf("%d", sizeof(NULL));
return 0;
}

Best Practices Related to NULL Pointers

  1. It is a good practise to initialize a pointer as NULL.
  2. It is a good practise to perform NULL check before dereferencing any pointer to avoid surprises.


This article on NULL Pointer in C is contributed by Rajnish Kumar. If you like TheCode11, then do follow us on Facebook, Twitter and Instagram.

Post a Comment

Previous Post Next Post

Contact Form