NULL Pointer Indirection in C with Examples

What is Indirection?

Indirection refers to accessing the value that a pointer points to. In C, this is done using the dereference operator *. For example:​

int x = 25;
int *ptr = &x;
printf("%d", *ptr); // Outputs: 25

Here, *ptr accesses the value of x through the pointer ptr.

What is NULL Pointer Indirection?

NULL pointer indirection occurs when you attempt to dereference a NULL pointer. Since the pointer doesn’t point to a valid memory location, dereferencing it leads to undefined behavior.

Example of NULL Pointer Indirection

#include <stdio.h>
 
int main()
{
    int *ptr = NULL;
 
    // Attempting to dereference a NULL pointer (NULL pointer indirection)
    printf("Value: %d\n", *ptr);  // Causes a crash (segmentation fault)
 
    return 0;
}

In this example, the pointer ptr is set to NULL, meaning it doesn’t point to any valid memory. When the program tries to access *ptr, it crashes with a segmentation fault.

advertisement

Consequences of NULL Pointer Indirection

Dereferencing a NULL pointer can lead to:​

  • Segmentation Faults: Accessing invalid memory regions can cause the operating system to terminate the program.​
  • Undefined Behavior: The behavior is unpredictable and may vary across systems.
  • Security Vulnerabilities: Attackers can exploit NULL pointer dereferences to execute arbitrary code or cause denial-of-service attacks.​​​

Common Scenarios Leading to NULL Pointer Indirection

1. Uninitialized Pointers:

int *ptr;
*ptr = 7; // ptr is uninitialized

Accessing *ptr without initializing it can lead to undefined behavior.

Note: Join free Sanfoundry classes at Telegram or Youtube

2. Memory Allocation Failures:

int *ptr = malloc(sizeof(int));
if (ptr == NULL) {
    // malloc failed
}
*ptr = 10; // Potential NULL dereference if not checked

Always check if malloc() succeeded before using the pointer.

3. Function Returns NULL:

int *getData() {
    return NULL;
}
int *data = getData();
*data = 20; // Dereferencing NULL

Ensure that functions returning pointers do not return NULL before dereferencing.

Best Practices to Avoid NULL Pointer Indirection

  • Initialize Pointers: Set them to NULL or a valid address initially.
  • Check Before Dereferencing: Verify that a pointer is not NULL before accessing its value.​​​
  •   if (ptr != NULL) {
          // Safe to dereference
          *ptr = 5;
      }
  • Handle Memory Allocation Failures: Always check the result of malloc or similar functions.​​​​
  • Use Static Analysis Tools: Tools like Valgrind can help detect invalid memory accesses.​​​​
  • Avoid Using Freed Memory: After freeing memory, set the pointer to NULL to prevent accidental dereferencing.​​​​
  •   free(ptr);
      ptr = NULL;

Pros and Cons of Using NULL Pointers

Pros of Using NULL Pointers

advertisement
  • Indicates Unused or Uninitialized State: Setting a pointer to NULL shows clearly that it doesn’t point to any valid data, which improves readability and safety.
  • Improves Error Handling: Before using a pointer, you can check if it’s NULL. This prevents potential crashes due to invalid memory access.
  • Used as a Sentinel Value: NULL is often used to signal special conditions, like failure in memory allocation or the end of data structures (e.g., linked lists or trees).
  • Supports Defensive Programming: Initializing pointers to NULL helps catch bugs early by making it easier to detect incorrect usage of pointers.

Cons of NULL Pointer Indirection

  • Crashes Your Program: If you try to use or access memory through a NULL pointer, your program can crash immediately — often with a segmentation fault.
  • Hard to Track Bugs: NULL pointer issues may not show up during compilation. They usually pop up while the program is running, making them harder to find and fix.
  • Security Vulnerabilities: Attackers can take advantage of NULL pointer issues to exploit a program and make it behave in unexpected or dangerous ways.
  • Requires Extra Caution: You have to manually check if a pointer is NULL before using it, adding more responsibility and code for the developer.
  • No Compile-Time Protection: Unlike some modern languages, C doesn’t warn you about possible NULL dereferencing while you’re writing the code.

Sanfoundry Global Education & Learning Series – 1000 C Tutorials.

If you wish to look at all C Tutorials, go to C Tutorials.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.