- C Programming Tutorial
- C - Home
- Basics of C
- C - Introduction
- C - Features
- C - Basics
- C - History
- C - Structure of C Program
- C - Program Structure
- C - Hello World
- C - Compilation Process
- C - Comments
- C - Tokens
- C - Keywords
- C - Identifiers
- C - User Input
- C - Basic Syntax
- C - Data Types
- C - Variables
- C - Integer Promotions
- C - Type Conversion
- C - Type Casting
- C - Booleans
- Constants and Literals in C
- C - Constants
- C - Literals
- C - Escape sequences
- C - Format Specifiers
- Operators in C
- C - Operators
- C - Arithmetic Operators
- C - Relational Operators
- C - Logical Operators
- C - Bitwise Operators
- C - Assignment Operators
- C - Unary Operators
- C - Increment and Decrement Operators
- C - Ternary Operator
- C - sizeof Operator
- C - Operator Precedence
- C - Misc Operators
- Decision Making in C
- C - Decision Making
- C - if statement
- C - if...else statement
- C - nested if statements
- C - switch statement
- C - nested switch statements
- Loops in C
- C - Loops
- C - While loop
- C - For loop
- C - Do...while loop
- C - Nested loop
- C - Infinite loop
- C - Break Statement
- C - Continue Statement
- C - goto Statement
- Functions in C
- C - Functions
- C - Main Function
- C - Function call by Value
- C - Function call by reference
- C - Nested Functions
- C - Variadic Functions
- C - User-Defined Functions
- C - Callback Function
- C - Return Statement
- C - Recursion
- Scope Rules in C
- C - Scope Rules
- C - Static Variables
- C - Global Variables
- Arrays in C
- C - Arrays
- C - Properties of Array
- C - Multi-Dimensional Arrays
- C - Passing Arrays to Function
- C - Return Array from Function
- C - Variable Length Arrays
- Pointers in C
- C - Pointers
- C - Pointers and Arrays
- C - Applications of Pointers
- C - Pointer Arithmetics
- C - Array of Pointers
- C - Pointer to Pointer
- C - Passing Pointers to Functions
- C - Return Pointer from Functions
- C - Function Pointers
- C - Pointer to an Array
- C - Pointers to Structures
- C - Chain of Pointers
- C - Pointer vs Array
- C - Character Pointers and Functions
- C - NULL Pointer
- C - void Pointer
- C - Dangling Pointers
- C - Dereference Pointer
- C - Near, Far and Huge Pointers
- C - Initialization of Pointer Arrays
- C - Pointers vs. Multi-dimensional Arrays
- Strings in C
- C - Strings
- C - Array of Strings
- C - Special Characters
- C Structures and Unions
- C - Structures
- C - Structures and Functions
- C - Arrays of Structures
- C - Self-Referential Structures
- C - Lookup Tables
- C - Dot (.) Operator
- C - Enumeration (or enum)
- C - Structure Padding and Packing
- C - Nested Structures
- C - Anonymous Structure and Union
- C - Unions
- C - Bit Fields
- C - Typedef
- File Handling in C
- C - Input & Output
- C - File I/O (File Handling)
- C Preprocessors
- C - Preprocessors
- C - Pragmas
- C - Preprocessor Operators
- C - Macros
- C - Header Files
- Memory Management in C
- C - Memory Management
- C - Memory Address
- C - Storage Classes
- Miscellaneous Topics
- C - Error Handling
- C - Variable Arguments
- C - Command Execution
- C - Math Functions
- C - String Functions
- C - Static Keyword
- C - Random Number Generation
- C - Command Line Arguments
C Programming - C NULL Pointer
![]() Share with a Friend |
C Programming - C NULL Pointer
C NULL Pointer
A NULL pointer is a pointer that does not point to any valid memory location. It is essentially used to signify that the pointer is not assigned to any valid memory address. In C, a NULL pointer is often used for error handling, indicating that a pointer variable has not yet been assigned a valid memory location, or for sentinel values in data structures.
- NULL Pointer Definition:
In C, a NULL pointer is defined in several ways, but the most common definition is:
C
#define NULL ((void *)0)
This definition ensures that NULL is the constant representing a pointer that points to nothing.
Alternatively, you can directly assign NULL as:
C
ptr = NULL;
- How NULL Pointer Works:
A NULL pointer holds the value 0 (or (void*)0), which indicates that the pointer is not pointing to any valid memory location. Using NULL pointers in programs helps to avoid undefined behavior and allows checking whether a pointer is valid or not before dereferencing it.
- Assigning NULL to a Pointer:
You can assign the NULL pointer to any pointer variable to indicate that it is not pointing to a valid object.
C
#include <stdio.h>
int main() {
int *ptr = NULL; // Initialize a pointer to NULL
if (ptr == NULL) {
printf("The pointer is NULL.\n");
} else {
printf("The pointer is not NULL.\n");
}
return 0;
}
Output:
The pointer is NULL.
Here, the pointer ptr is assigned to NULL, and the program checks whether the pointer is NULL.
- Dereferencing a NULL Pointer:
Dereferencing a NULL pointer leads to undefined behavior and can cause the program to crash (segmentation fault). It is critical to always check if a pointer is NULL before dereferencing it.
C
#include <stdio.h>
int main() {
int *ptr = NULL;
// Dereferencing a NULL pointer is dangerous and should be avoided
// Uncommenting the next line will cause a crash or undefined behavior:
// printf("%d", *ptr); // Dangerous: Dereferencing NULL pointer
return 0;
}
Attempting to dereference a NULL pointer, like *ptr when ptr is NULL, will lead to a crash or unpredictable behavior.
- Common Uses of NULL Pointer:
- Error Handling: NULL pointers are commonly used in error handling to indicate failure or that memory could not be allocated.
C
#include <stdio.h>
#include <stdlib.h>
int *allocateMemory(int size) {
int *ptr = (int *)malloc(size * sizeof(int));
if (ptr == NULL) {
printf("Memory allocation failed!\n");
return NULL; // Return NULL if memory allocation fails
}
return ptr;
}
int main() {
int *arr = allocateMemory(5);
if (arr == NULL) {
// Handle memory allocation failure
return 1; // Exit if memory allocation failed
}
// Continue using arr as normal
free(arr); // Free allocated memory
return 0;
}
- Function Return: A function may return NULL to signify that it was unable to perform an operation or return a valid result.
C
int* findMax(int arr[], int size) {
if (size <= 0) {
return NULL; // Return NULL if the array size is invalid
}
int *max = &arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] > *max) {
max = &arr[i];
}
}
return max;
}
- Linked Lists and Data Structures: NULL is commonly used to mark the end of a list in data structures like linked lists.
C
struct Node {
int data;
struct Node *next;
};
int main() {
struct Node *head = NULL; // Initializing an empty linked list
// Check if the list is empty
if (head == NULL) {
printf("The list is empty.\n");
}
return 0;
}
In this case, the next pointer of the last node in a linked list would be NULL, signaling the end of the list.
- Checking for NULL Pointers:
Before dereferencing a pointer, it is a good practice to check if it is NULL to avoid segmentation faults or undefined behavior.
C
#include <stdio.h>
void printValue(int *ptr) {
if (ptr != NULL) {
printf("Value: %d\n", *ptr);
} else {
printf("Pointer is NULL, cannot dereference.\n");
}
}
int main() {
int *ptr = NULL;
printValue(ptr); // Safe check before dereferencing
return 0;
}
Output:
Pointer is NULL, cannot dereference.
By checking for NULL before dereferencing, we ensure that our program behaves safely and avoids crashes.
Key Takeaways:
- NULL pointer is a pointer that doesn't point to any valid memory location.
- It is defined as #define NULL ((void*)0) in C.
- Dereferencing a NULL pointer causes undefined behavior (usually a crash).
- NULL pointers are useful for error handling, checking uninitialized pointers, or indicating the end of data structures (e.g., linked lists).
- Always check for NULL before dereferencing pointers to prevent runtime errors.
Using NULL pointers effectively helps in robust and error-free C programming, especially when dealing with dynamic memory allocation and linked data structures.
