C/C++ Arena

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:

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 turn: write int safe_get(const int *p, int fallback) that returns *p, or fallback if p is NULL.

Previous: Pointer arithmetic and arrays Next: Strings through pointers