Back to: C Tutorials For Beginners and Professionals
Null Pointer in C Language with Examples
In this article, I will discuss Null Pointer in C Language with Examples. Please read our previous articles discussing Pointer to Constant in C Language with Examples.
What is a Null Pointer?
In C programming, a null pointer is a pointer that does not point to any valid memory location. It’s a special type of pointer used to indicate that it is not intended to point to an accessible memory location. Using a null pointer is essential for error handling and to avoid undefined behavior caused by uninitialized or dangling pointers. A null pointer is a special reserved value defined in a stddef header file.
If we do not have any address which is to be assigned to the pointer, then it is known as a null pointer. When a NULL value is assigned to the pointer, it is considered a Null pointer. So, A null pointer is a pointer that points to nothing. Some uses of the null pointer are as follows:
- Used to initialize a pointer variable when that pointer variable isn’t assigned any valid memory address yet.
- Used to pass a null pointer to a function argument when we don’t want to pass any valid memory address.
- Used to check for a null pointer before accessing any pointer variable. So that we can perform error handling in pointer-related code, e.g., dereference pointer variable only if it’s not NULL.
Characteristics of a Null Pointer in C Language:
- Initialization: A null pointer is typically initialized using the macro NULL, defined in several standard libraries, like <stddef.h>, <stdio.h>, <stdlib.h>, and others.
- Comparison: A null pointer can be compared against other pointers. It is often used in conditions to check whether a pointer is valid.
- Assignment: Any pointer can be assigned NULL.
- Dereferencing: Dereferencing a null pointer leads to undefined behavior, often resulting in a runtime error or a program crash.
Null Pointer in C Language:
The pointer variable, initialized with the null value, is called the Null Pointer. Null Pointer doesn’t point to any memory location until we are not assigning the address. The size of the Null pointer is also 2 bytes, according to the DOS Compiler.
Example Usage of Null Pointers
Here’s a simple example demonstrating the use of null pointers:
#include <stdio.h> #include <stdlib.h> int main() { int *ptr = NULL; // Initialize the pointer to NULL // Check if the pointer is null before dereferencing if (ptr == NULL) { printf("The pointer is null and will not be dereferenced.\n"); } else { printf("The value pointed to by ptr is %d\n", *ptr); } // Dynamic memory allocation ptr = (int*)malloc(sizeof(int)); if (ptr != NULL) { *ptr = 10; printf("Dynamic memory allocated. Value = %d\n", *ptr); free(ptr); } return 0; }
When to Use Null Pointers in C Language?
- Initialization: Initialize pointers to NULL when they are declared but not yet assigned to a specific memory address. This prevents them from becoming dangling pointers.
- After free: Set pointers to NULL after freeing dynamically allocated memory to prevent dangling pointers.
- Error Handling: Return NULL from functions to indicate an error when the function is supposed to return a pointer.
- End of Data Structures: In linked lists, trees, and similar data structures, null pointers often signify the end of the structure or an empty node.
- Conditional Checks: Check whether a pointer is NULL before dereferencing it to ensure that it points to valid memory.
Example: Initializing and Checking a Null Pointer
#include <stdio.h> int main() { int *ptr = NULL; // Initializing a null pointer if (ptr == NULL) { printf("The pointer is null.\n"); } else { printf("The pointer is not null.\n"); } return 0; }
In this example, ptr is initialized to NULL and then checked. The program will print “The pointer is null.”
Example: Using Null Pointers in Function Return
A common use case for null pointers is in functions that return pointers. A null pointer can signal an error or a special condition.
#include <stdio.h> #include <stdlib.h> int* allocateMemory(size_t size) { int *ptr = malloc(size); if (ptr == NULL) { // Allocation failed return NULL; } return ptr; } int main() { int *ptr = allocateMemory(0); // Intentionally passing 0 to cause failure if (ptr == NULL) { printf("Memory allocation failed.\n"); } else { // Use the memory free(ptr); } return 0; }
Here, allocateMemory returns NULL if memory allocation fails. The main function checks the returned pointer and prints a message accordingly.
Example: Null Pointers in Linked Lists
Null pointers are frequently used in data structures like linked lists to mark the end of the list.
#include <stdio.h> #include <stdlib.h> typedef struct Node { int data; struct Node *next; } Node; int main() { Node *head = NULL; // Empty linked list // Normally, nodes would be added here if (head == NULL) { printf("The list is empty.\n"); } return 0; }
In this example, head is a null pointer indicating that the linked list is initially empty.
Key Points:
- A null pointer does not point to any valid memory location.
- It’s a good practice to initialize pointers to NULL until they are assigned a valid address.
- Always check if a pointer is null before dereferencing it to avoid runtime errors.
- Null pointers are a key part of many data structures and algorithms in C.
Null Pointer use Cases in C Language:
When we do not assign any memory address to the pointer variable.
In the below example, we declare the pointer variable *ptr, but it does not contain the address of any variable. The dereferencing of the uninitialized pointer variable will show the compile-time error as it does not point to any variable. The following C program shows some unpredictable results and causes the program to crash. Therefore, we can say that keeping an uninitialized pointer in a program can cause the program to crash.
#include <stdio.h> int main() { int *ptr; printf ("Address: %d", ptr); // printing the value of ptr. printf ("Value: %d", *ptr); // dereferencing the illegal pointer return 0; }
How do we avoid the above problem?
We can avoid the problem in C Programming Language by using a Null pointer. A null pointer points to the 0th memory location, a reserved memory that cannot be dereferenced. In the below example, we create a pointer *ptr and assign a NULL value to the pointer, which means that it does not point to any variable. After creating a pointer variable, we add the condition in which we check whether the value of a pointer is null or not.
#include <stdio.h> int main() { int *ptr = NULL; if (ptr != NULL) { printf ("value of ptr is : %d", *ptr); } else { printf ("Invalid pointer"); } return 0; }
When we use the malloc() function?
In the below example, we use the built-in malloc() function to allocate the memory. If the malloc() function is unable to allocate the memory, then it returns a NULL pointer. Therefore, it is necessary to add the condition to check whether the value of a pointer is null. If the value of a pointer is not null, it means that the memory is allocated.
#include <stdio.h> int main() { int *ptr; ptr = (int *) malloc (5 * sizeof (int)); if (ptr == NULL) { printf ("Memory is not allocated"); } else { printf ("Memory is allocated"); } return 0; }
Note: It is always a good programming practice to assign a Null value to the pointer when we do not know the exact address of memory.
Applications of Null Pointer
Following are the applications of a Null pointer:
- It is used to initialize the pointer variable when the pointer does not point to a valid memory address.
- It is used to perform error handling with pointers before dereferencing the pointers.
- It is passed as a function argument and returned from a function when we do not want to pass the actual memory address.
In the next article, I will discuss Void Pointer in C Language with Examples. In this article, I try to explain Null Pointers in C Language with Examples. I hope you enjoy this Null Pointer in C Language with Examples article. I would like to have your feedback. Please post your feedback, questions, or comments about this article.