Course contentsShow
← C
Lesson 462 of 1,2197. PointersFree lesson

Checking for NULL before dereferencing

Checking for NULL before dereferencing

What you'll learn: How to safeguard your programs against crashes by verifying that a pointer actually points to a valid memory address before you try to use it.

The "Empty Envelope" Problem

Imagine you are a mail carrier. You are given an envelope that is supposed to contain a house address. You are told: "Go to the address inside this envelope and paint the front door red."

You open the envelope, but the paper inside is completely blank. If you try to follow your instructions, you’ll wander aimlessly, get lost, or walk into a brick wall because there is no destination.

In C, a pointer that contains NULL is like that blank piece of paper. It represents "nowhere." If you try to dereference it (using the * operator to access the value at that address), your program doesn't just get confused—it crashes immediately with a "Segmentation Fault."

The Golden Rule of Safety

Because pointers can often be empty—perhaps because a memory allocation failed or a function couldn't find what it was looking for—you must develop the habit of "looking before you leap."

In code, this means wrapping your pointer logic in a simple if statement. If the pointer is not NULL, it is safe to proceed. If it is NULL, you should handle the error gracefully instead of letting the program crash.

Defensive Coding in Action

Here is how you check a pointer before dereferencing it:

#include <stdio.h>

int main() {
    int *ptr = NULL; // A pointer pointing to nothing

    // WRONG: Trying to do *ptr = 10; here would crash the program.

    // RIGHT: The safety check
    if (ptr != NULL) {
        printf("The value is: %d\n", *ptr);
    } else {
        printf("Error: Pointer is NULL. Cannot dereference!\n");
    }

    return 0;
}

In the example above, the if statement acts as a gatekeeper. By checking ptr != NULL, you ensure that the *ptr operation only happens when there is a valid destination to visit.

Why This Matters

As your programs grow, functions will frequently return NULL to signal that something went wrong. If you assume every pointer is valid without checking, your code becomes a minefield of potential crashes. Checking for NULL is the simplest and most effective way to write "robust" code that handles errors without breaking.

Key takeaway

Always verify that a pointer is not NULL before using the * operator to access its value.