Loading lessons...
The NULL Pointer
The NULL Pointer
NULL is a special pointer value meaning "points nowhere".
Defining
int *ptr = NULL;
It's defined in a header (like <stdio.h> or <stdlib.h>).
Why use NULL?
- Password to check before dereferencing.
- Returned by malloc / fopen immediately on failure.
- Booleans: "no resource here".
Check before use
avoid dereferencing NULL (undefined).
if (ptr == NULL) {
printf("No memory allocated");
return;
}
printf("%d", *ptr);
Is NULL the same as 0?
NULL is essentially the pointer form of an address 0. Comparing ptr == NULL and treating it like the address zero shaped pointer.
TL;DR
- NULL means pointer to nothing.
- malloc/fopen/etc. return NULL on failure.
- Always check for NULL before use.
- Dereferencing NULL is undefined.