C NULL
๐น C NULL
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:
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
This causes a segmentation fault.
โ NULL vs 0
In C, NULL is often defined as:
But semantically:
-
0is an integer -
NULLis a pointer constant
So use NULL for pointers:
๐ 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 |
