NULL
- C course
- Beginner
- Lesson 74/116
- 5 min
Learn the NULL pointer concept and safety.
The NULL pointer
NULL is a special pointer value that points nowhere. It is defined in stdlib.h or stddef.h.
int *ptr = NULL; /* ptr is empty */
if (ptr == NULL) {
printf("Empty\n");
}Initializing a pointer to NULL states explicitly that it does not point anywhere yet. This prevents invalid access and improves readability.
Checking for NULL
To check whether a pointer is NULL, use ==. Accessing a non-NULL pointer with * is safe.
int x = 5;
int *ptr = &x;
if (ptr != NULL) {
printf("%d\n", *ptr); /* prints 5 */
}Accessing a NULL pointer with * is undefined behavior; the program may crash. So the check is essential.
Practice Safe access with a NULL check
Define int x = 42;. Bind with int *ptr = &x;. Inside if (ptr != NULL), call printf("%d\n", *ptr);. Output should be 42.
Starter code
#include <stdio.h>
#include <stddef.h>
int main(void) {
int x = 42;
/* bind ptr to x */
/* if not NULL, print *ptr */
return 0;
}Sample solution
#include <stdio.h>
#include <stddef.h>
int main(void) {
int x = 42;
int *ptr = &x;
if (ptr != NULL) {
printf("%d\n", *ptr);
}
return 0;
}Expected output
42
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Why is initializing a pointer to NULL a good idea?
- Speeds it up
- Allocates memory
- Speeds up the compiler Correct answer
- Prevents invalid access
Explanation: NULL makes it explicit that the pointer is not yet pointing anywhere; this prevents invalid access.
2 NULL check
int *ptr = NULL;
if (ptr ____) { /* ptr is null */ }
int *ptr = NULL;
if (ptr == NULL) { /* ptr is null */ }
Explanation: ptr == NULL checks for null.
3 Match NULL concepts
| Term | Meaning |
|---|---|
NULL |
null pointer |
== NULL |
null check |
!= NULL |
not-null check |
*ptr |
value access |