C Null Pointer
A NULL pointer in C is a pointer that doesn’t point to any valid memory location. It acts as a special value to show that a pointer is either not initialized yet or is pointing to an invalid or unavailable memory address.
Syntax
In C, the NULL pointer is defined in the <stddef.h> header file. It is typically assigned to a pointer to indicate that it is not pointing to any valid memory.
#include <stddef.h>
pointer_type *pointer_name = NULL;
pointer_type: The data type of the pointer .pointer_name: The name of the pointer.
Example
In the example, we declare an integer pointer ptr and initialize it to NULL, indicating that it doesn’t point to any valid memory location:
#include <stdio.h>#include <stddef.h>int main() {int *ptr = NULL; // Initialize pointer to NULLif (ptr == NULL) {printf("Pointer is NULL\n");}return 0;}
The if statement checks if ptr is NULL, if true, it prints “Pointer is NULL” to the screen. This ensures the pointer is not used before properly initialising to a valid memory address.
Usage
1. Initializing Pointers
It is a common practice to initialize pointers to NULL to avoid them pointing to random or undefined memory locations. This helps prevent undefined behavior caused by dereferencing uninitialized or dangling pointers.
int *ptr = NULL;
2. Pointer Checking
Before dereferencing a pointer, it is a good practice to check whether it is NULL. Dereferencing a NULL pointer will cause a segmentation fault, leading to runtime errors.
if (ptr != NULL) {// Safe to dereference ptrprintf("%d", *ptr);} else {printf("Pointer is NULL\n");}
3. Return Value for Failure
Functions that involve memory allocation or searching operations often return a NULL pointer to indicate failure. For example, when using .malloc() to allocate memory, if the allocation fails, it returns NULL.
int *ptr = malloc(sizeof(int));if (ptr == NULL) {printf("Memory allocation failed!\n");}
4. NULL vs. 0
In C, NULL is often defined as ((void \*)0). While NULL and 0 can be used interchangeably in many contexts, using NULL improves code readability, making it clear that the value is a pointer rather than an integer.
Best Practices
- Always initialize pointers to
NULLto avoid pointing to garbage memory. - Always check for
NULLbefore dereferencing pointers. - Use
NULLas a return value for functions that encounter errors or failure in memory allocation. - Avoid using pointer arithmetic on
NULL.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours