Null Pointer in C

By | February 18, 2023

In C programming language, a null pointer is a pointer that has a value of “null”, or “0”. A null pointer is a pointer that does not point to any memory location. It is often used to indicate that a pointer is not currently pointing to a valid memory location.

Uses of NULL Pointer in C :
Null pointers are commonly used in C for various purposes, such as initializing pointers, testing pointers for validity, and terminating linked lists. Here are some examples of how null pointers are used in C:

1. Initializing pointers –
When declaring a pointer, it is a good practice to initialize it to a null value. This ensures that the pointer is not pointing to an arbitrary memory location. Here’s an example:

int *ptr = NULL;

This initializes the pointer “ptr” to a null value.

2. Testing for validity –
Null pointers are commonly used to test whether a pointer is valid or not. This can be done using a simple if-statement. Here’s an example:

int *ptr = NULL;
if (ptr == NULL) {
    printf("Pointer is null\n");
} else {
    printf("Pointer is not null\n");
}

This checks whether “ptr” is a null pointer or not, and prints a message accordingly.

3. Terminating linked lists –
In C, linked lists are often terminated with a null pointer. This indicates the end of the list, and prevents the program from accessing invalid memory. Here’s an example:

struct node {
    int data;
    struct node *next;
};

struct node *head = NULL;
struct node *curr = NULL;
while (condition) {
    struct node *new_node = (struct node*)malloc(sizeof(struct node));
    new_node->data = value;
    new_node->next = NULL;

    if (head == NULL) {
        head = new_node;
        curr = new_node;
    } else {
        curr->next = new_node;
        curr = new_node;
    }
}

This creates a linked list of nodes, and sets the “next” field of the last node to a null pointer, indicating the end of the list.

Note:
It’s important to note that when working with null pointers, it’s important to check for null values before attempting to dereference the pointer. Dereferencing a null pointer can result in undefined behavior, such as a segmentation fault or a system crash.

Please write comments below if you find anything incorrect, or you want to share more information about the topic discussed above. A gentle request to share this topic on your social media profile.

Author: Mithlesh Upadhyay

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.