• Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard
CSEstack

What do you want to Learn Today?

  • Programming
    • Tutorial- C/C++
    • Tutorial- Django
    • Tutorial- Git
    • Tutorial- HTML & CSS
    • Tutorial- Java
    • Tutorial- MySQL
    • Tutorial- Python
    • Competitive Coding Challenges
  • CSE Subject
    • (CD) Compiler Design
    • (CN) Computer Network
    • (COA) Computer Organization & Architecture
    • (DBMS) Database Management System
    • (DS) Data Structure
    • (OS) Operating System
    • (ToA) Theory of Automata
    • (WT) Web Technology
  • Interview Questions
    • Interview Questions- Company Wise
    • Interview Questions- Coding Round
    • Interview Questions- Python
    • Interview Questions- REST API
    • Interview Questions- Web Scraping
    • Interview Questions- HR Round
    • Aptitude Preparation Guide
  • GATE 2022
  • Linux
  • Trend
    • Full Stack Development
    • Artificial Intelligence (AI)
    • BigData
    • Cloud Computing
    • Machine Learning (ML)
  • Write for Us
    • Submit Article
    • Submit Source Code or Program
    • Share Your Interview Experience
  • Tools
    • IDE
    • CV Builder
    • Other Tools …
  • Jobs

3 Major use of NULL Pointer in C Programming | What does actually NULL means?

Aniruddha Chaudhari/41088/7
C / C++Code

Understanding the NULL pointer is easy but not so if you are implementing in your code. At the end of this post, you will learn to avoid NULL pointer problems and handling them gracefully.

Following are the topics covered in this article.

Table of Contents

  • What is a NULL?
  • What is a NULL Pointer?
  • Why do we need a NULL Pointer?
  • Best Practices to use NULL Pointer
  • What is the use of NULL Pointer in C?
  • Difference Between NULL and Void Pointer
  • Usage of a NULL Pointer in Various Programming Languages

So let’s begin…

What is NULL?

It is a special marker or keyword which has no value.

Each programming language has its own nuance.

In most of the programming language including C, Java, typically, 0 (zero) is a NULL and predefined constant or Macro.

NULL is a value that is not a value. Confusing, right?

Here is a simple example to differentiate.

In C++ programming,

char *par = 123; is not valid and gives a compilation error. Compiler except passing a hexadecimal value to the pointer and we are passing integer value.

Whereas char *par = 0; is a valid statement. Here, 0 (zero) is a null in C++ programming. As null does not have any value, the compiler can not discriminate.

For this reason, C.A.R Hoare (inventor of Null) said that inventing the NULL pointer was his biggest mistake. We leave this here, as it is not the scope of this article.

Moving to…

What is a NULL Pointer?

Whenever you assign any data to the variable, it gets stored at a particular location in the physical memory. This memory location has unique address value in hexadecimal format (something like 0x006CoEEA8).

The variable that stores this memory address is called as a Pointer.

When you assign a NULL value to the pointer, it does not point to any of the memory locations. The null pointer is nothing but the pointer which points to nothing.

It is also called as a NULL macro.

Here is a simple C program to print the value of NULL macro.


#include<stdio.h>
void main()
{
    printf("Value of NULL: %d", NULL);
     //Value of NULL: 0
}

We can use this NULL constant value to assign to any pointer so that it will not point to any of the memory locations.

Here is the simple syntax for declaring a NULL pointer.

int *ptr = NULL;

Here, ptr is a NULL pointer.

We can also assign 0 directly to the pointer.

int *ptr = 0;

This is also a valid expression in C. But, it is a standard practice to use a NULL constant.

The NULL constant is defined in many of the header files in the C programming language; including, stdio.h stddef.h, stdlib.h, etc.

In C programming, usually, we add stdio.h in the program to use scanf() and printf() functions. So, you don’t need to add any extra header files.

Later in the code, you can assign any memory location to ptr pointer.

Why do we need a NULL Pointer?

Whenever you declare a pointer in your program, it points to some random memory location. And when you try to retrieve the information at that location, you get some garbage values. Many time, you might have observed this.

Using this garbage value in the program or passing it to any function, your program may crash.

Here, NULL pointer comes handy.

I am describing the use of the NULL pointer in C programming by three different ways. Before that, let’s see the best practices to use NULL pointer in programming.

Best Practices for NULL Pointer Usage:

How to use a NULL pointer to avoid any errors in your programming?

  • Make a habit of assigning the value to a pointer before using it. Don’t use pointer before initializing it.
  • If you don’t have a valid memory address to store in a pointer variable, just initialize a pointer to NULL.
  • Before using a pointer in any of your function code, check if it has not a NULL value.

What is the use of NULL Pointer in C?

Above all understanding, this is the first question you ask yourself about the NULL pointer. Here are some use cases of NULL pointer…

1. Avoid Crashing a Program:

If you pass any garbage value in your code or to the particular function, your program can crash. To avoid this, you can use NULL pointer.

Before using any pointer, compare it with NULL value and check.


#include<stdio.h>

void fact(int *ptrB)
{
    if(ptrB == NULL)
    {
        //Handle NULL pointer input
        return;
    }
    else
    {
        //function code
    }
}
void main()
{
    int *ptrA = NULL;
    fact(ptrA);
}

In the above code, we are passing a pointer to fact() function. In fact() function, we are checking if the input pointer is NULL or not.

If the value of the pointer ptrA is not NULL, execute the function body.

Passing a NULL value to the function code without checking can terminate your program by crashing inside the function. So, it is one of the best use of NULL pointer in C.

2. While Freeing (de-allocating) Memory:

Suppose, you have a pointer which points to some memory location where data is stored. If you don’t need that data anymore, for sure, you want to delete that data and free the memory.

But even after freeing the data, pointer still points to the same memory location. This pointer is called as a dangling pointer. To avoid this dangling pointer, you can set the pointer to NULL.

Let’s check this below example to avoid dangling pointer in C.


#include<stdio.h>

void main()
{
    int *ptr = (int *)malloc(SIZE);
    //. . . . . .
    //. . . . . .

    free(ptr); 
    //ptr pointer is pointing to a dangling reference

    ptr=NULL; 
    //now ptr is not a dangling pointer
}

Here, malloc() is an inbuilt function to create a dynamic memory.

Pro Tips:
If you want to be a good programmer, always make habit of freeing up the memory if data is no longer use. 
If you are a mobile app developer, you have very limited memory space for your apps. 
It is always good practice to delete data as soon as you don't need it further.

What is the difference between NULL and Void Pointer?

Many of the programmer, especially beginners, get confused between NULL and void pointer.

The void is one of the data types in C. Whereas, NULL is the value which is assigned to the pointer.

The data type of the pointer is nothing but the type of data stored at the memory location where the pointer is pointed. When you are not sure about the type of data that is going to store at a particular memory location, you need to create the void pointer.

Below is an example for creating void pointer in C.


#include<stdio.h>

void main()
{
    void *ptr;  //Creating void pointer
    //. . . . . .
    //. . . . . .
}

3. NULL pointer Uses in Linked List:

A NULL pointer is also useful in Linked List. We know that in Linked List, we point one node to its successor node using a pointer.

Implement Linked List in C

As there is no successor node to the last node, you need to assign a NULL value to the link of the last node. (As shown in above image.)

Check the implementation of Linked List in C to know how NULL pointer is used. I have described it in detail.

This is all about NULL pointer in C and CPP programming. The understanding of the NULL pointer is a concept. Like C programming, you can see the same use cases of NULL pointers in many other programming languages.

Usage of a NULL pointer in various Programming Languages?

Many of the programming languages use the NULL pointer concept. It is not necessary to have the same name for a NULL pointer, but the concept is almost the same in all the programming languages.

  • In C, the NULL keyword is a predefined macro.
  • In C++, the NULL is inherited from C programming.
  • The latest development in C++11, there is an explicit pointer to handle the NULL exception, called null ptr constant.
  • In Java programming, there is a null value. It indicates that no value is assigned to a reference variable.
  • In some other programming language like Lips, it is called as nil vector.

Check out all the C and C++ programming questions. You will find NULL pointer and macro very useful.

This is all about NULL macro and use of NULL pointer in C programming. If you have any question, feel free to ask in a comment.

CcppNULL pointer
Aniruddha Chaudhari
I am complete Python Nut, love Linux and vim as an editor. I hold a Master of Computer Science from NIT Trichy. I dabble in C/C++, Java too. I keep sharing my coding knowledge and my own experience on CSEstack.org portal.

Your name can also be listed here. Got a tip? Submit it here to become an CSEstack author.

Comments

  • Reply
    Vatsal Kane
    May 31, 2017 at 12:17 am

    Great Post. Agree with Mathew. Many people learn about NULL pointer but many few uses them in their project.

    I think the NULL pointer is extremely useful to avoid the crash and for better programming.

    • Reply
      Aniruddha Chaudhari
      June 10, 2017 at 5:12 am

      You are absolutely right, Vatsal. Thanks for putting your thought.

  • Reply
    Mathew Wade
    May 31, 2017 at 11:18 pm

    I read about NULL pointer earlier, but this is very descriptive and you have mentioned very good use cases.

    Thanks Aniruddha.

    • Reply
      Aniruddha Chaudhari
      June 10, 2017 at 5:13 am

      Great to see you here Mathew. I am glad you like it.

      Cheers!

  • Reply
    Abha
    August 9, 2018 at 3:10 pm

    Very neatly explained. Thank you and keep up the good work. 🙂

    • Reply
      Aniruddha Chaudhari
      August 9, 2018 at 6:40 pm

      Thanks Abha for putting your thought 🙂 It keeps motivating me to work hard.

  • Reply
    Nadim
    February 9, 2021 at 10:30 pm

    Using this garbage value in the program or passing it to any function, your program may crash.

    #include
    
    void even(int *p)
    {
        int a=10;
        p=&a;
        printf("%d",*p);
    }
    int main()
    {
        int *p;
        even(p);
    }
    

    output is 10.
    It still works. My program is not crashed.

Leave a Reply Cancel reply

C Programming

  1. C- Introduction
  2. C- Compile & Execute Program
  3. C- Data Types
  4. C- if-else statement
  5. C- While, do-while, for loop
  6. C- Array
  7. C- Function (Types/Call)
  8. C- strlen() vs sizeof()
  9. C- Nested Switch Statement
  10. C- Recursion
  11. C- Dynamic Programming
  12. C- Storage Classes
  13. C- Creating Header File
  14. C- Null Pointer
  15. C- Stack and Queue
  16. C- Implement Stack using Array
  17. C- Implement Linked List in C
  18. C- File Handling
  19. C- Makefile Tutorial

Object Oriented Concepts in C++

  • C++: C vs OOPs Language
  • C++: Introduction to OOPs Concepts
  • C++: Inheritance

Sorting Algorithms

  • Different Types of Sorting Algo
  • Selection Sort
  • Bubble Sort
  • Quick Sort

Programming for Practice

  1. Online C/C++ Compiler

String Handling:

  1. Remove White Spaces from String
  2. Implement strstr Function in C
  3. Convert String to Int – atoi()
  4. Check if String is Palindrome
  5. Check if Two Strings are Anagram
  6. Split String in using strtok_r()
  7. Undefined reference to strrev

Array:

  1. Check if Array is Sorted

Bit Manipulation:

  1. Count Number of 1’s in Binary

Linked List:

  1. Reverse a Linked List Elements

Number System:

  1. Program to Find 2’s Complement
  2. Convert Decimal to Binary in C

Tricky Questions:

  1. Add Two Numbers without Operator
  2. Find Next Greater Number
  3. Swap values without temp variable
  4. Print 1 to 100 without Loop

Interview Coding Questions

  • 50+ Interview Coding Questions

© 2022 – CSEstack.org. All Rights Reserved.

  • Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard