Pointers
Null Pointers
A null pointer holds no usable object address, so code checks it before dereferencing.
null
`0` is a null pointer constant when assigned to a pointer.
guard
Check a pointer before using `*ptr`.
Null Pointers
null_pointers.c
Replay: real traced execution (multi-file project)
#include <stdio.h>
int main(void) {
int value = 9;
int useValue = 1;
int *ptr = 0;
if (useValue) {
ptr = &value;
}
if (ptr != 0) {
printf("value=%d\n", *ptr);
} else {
printf("value=missing\n");
}
return 0;
}
#include <stdio.h>
int main(void) {
int value = 9;
int useValue = 0;
int *ptr = 0;
if (useValue) {
ptr = &value;
}
if (ptr != 0) {
printf("value=%d\n", *ptr);
} else {
printf("value=missing\n");
}
return 0;
}
value ← 9, useValue ← 1, ptr ← 0
3int main(void) {4 int value→ 9 = 9;5 int useValue→ 1 = 1; //@useValue=06 int *ptr→ 0 = 0;ptr ← ⟨addr A⟩
8if (useValue1) {9 ptr→ ⟨addr A⟩ = &value9;10}if (ptr != 0)
12if (ptr⟨addr A⟩ != 0) {13 printf("value=%d\n", *ptr⟨addr A⟩);14} else {outputvalue=9return 0;
18 return 0;19}
value ← 9, useValue ← 0, ptr ← 0
3int main(void) {4 int value→ 9 = 9;5 int useValue→ 0 = 0;6 int *ptr→ 0 = 0;else
13 printf("value=%d\n", *ptr);14} else {15 printf("value=missing\n");16}outputvalue=missingreturn 0;
18 return 0;19}
Check Before Use
- A pointer either stores a real address or
0. 0means there is no object to read.- Test the pointer before using
*ptr. - Only the non-null branch should dereference it.
| Pointer value | Safe next step |
| --- | --- |
| Real address | Use
*ptr. | |0| Return or print an error. |
Exercise: null_pointers.c
Guard a pointer before dereferencing it and return an error status when the pointer is null