C NULL

C Tutorial

🔹 C NULL

C NULL is a special constant in C used to represent a null pointer, meaning the pointer does not point to any valid memory location.

It is defined in multiple header files such as:



 


✅ What is NULL?

NULL stands for “no value” or “empty pointer”.

Example:

int *ptr = NULL;

This means ptr is declared but doesn’t point to any memory address.


🧠 Why Use NULL?

NULL helps avoid:

  • Dangling pointers

  • Invalid memory access

  • Unpredictable program crashes

Using NULL makes it easy to test whether a pointer has a valid address.


📌 Checking NULL Pointer


 


🧪 Example With Dynamic Memory


 

💡 After freeing memory, setting pointer to NULL prevents accidental reuse.


🔥 NULL vs Uninitialized Pointer

Pointer State Example Safe?
NULL pointer int *p = NULL; ✔ Safe to check
Uninitialized pointer int *p; ❌ Dangerous

Uninitialized pointers hold garbage values, which may point to invalid or system memory.


🚨 Don’t Dereference a NULL Pointer

int *ptr = NULL;
printf("%d", *ptr); // ❌ runtime error

This causes a segmentation fault.


✔ NULL vs 0

In C, NULL is often defined as:

#define NULL 0

But semantically:

  • 0 is an integer

  • NULL is a pointer constant

So use NULL for pointers:

int *p = NULL; // correct
int *p = 0; // works, but not recommended

🏁 Summary

Concept Meaning
NULL Special value indicating no valid address
Used with Pointers
Common use Checking valid memory before access
Prevents Crashes and undefined behavior

You may also like...