Step 5 of 10
NULL
Sometimes a pointer needs to say "I'm not pointing at anything right now". For that, C has NULL: a special pointer value guaranteed not to be the address of any real object. It's defined in <stddef.h> (and several other headers).
Typical uses:
- A search function returns
NULLwhen it finds nothing. - An optional parameter can be
NULLto mean "not provided". - The last node of a linked list has a
nextpointer ofNULL. - A pointer that has been freed is set to
NULLso nobody uses it by accident.
Never dereference NULL
Following a NULL pointer is undefined behavior. On desktop operating systems it usually crashes the program immediately with a segmentation fault. But undefined means anything can happen: in WebAssembly, which runs your code on this site, address 0 is ordinary memory, so reading through NULL here may quietly give you 0 instead of crashing. The same bug can crash on one machine and silently produce wrong answers on another, which is exactly why you must never rely on it. Whenever a pointer might be NULL, check it before using it:
#include <stdio.h>
#include <stddef.h>
void print_score(const int *score) {
if (score == NULL) {
printf("no score yet\n");
return;
}
printf("score %d\n", *score);
}
int main(void) {
int s = 42;
print_score(&s);
print_score(NULL);
return 0;
}
score 42
no score yet
Style
if (p != NULL) and if (p) mean the same thing, because NULL compares equal to 0 (false). Many C programmers write the short form. Checking early and returning (a guard clause) keeps the rest of the function simple, since it can assume the pointer is valid.
Your task
Write int safe_get(const int *p, int fallback) that returns *p, or fallback if p is NULL.
Challenge 2
Write int safe_div(int a, int b, int *out). If b is 0 or out is NULL, return 0 and do nothing else. Otherwise store a / b in *out and return 1.
Challenge 3
Write const char *display_name(const char *name) that returns name, or "anonymous" if name is NULL or an empty string. Check for NULL before looking at the first character.
Previous: Pointer arithmetic and arrays Next: Strings through pointers