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

Dereferencing the NULL pointer

Dereferencing the NULL pointer

What you'll learn: How to avoid the most common cause of program crashes by ensuring your pointers actually point to valid data before you use them.

The "Address Unknown" Trap

In previous lessons, you learned that a pointer is simply a variable that holds a memory address. You also learned that NULL is a special constant representing "nothing." It is the intentional absence of an address.

Think of a pointer like a physical mailing address written on a sticky note. If the note says "123 Maple St," you can go there and open the mailbox. However, a NULL pointer is like a blank sticky note. If you try to "go to" a blank note and open a mailbox that doesn't exist, the universe—or in this case, the Operating System—doesn't know what to do.

In C, trying to access or modify the value at a NULL address is called dereferencing a NULL pointer. Because NULL points to memory that your program is strictly forbidden from touching, the computer protects itself by instantly killing your program. This is the dreaded "Segmentation Fault."

Defending your code

Safe C programming relies on a simple rule: Always verify before you dereference. Since functions like malloc() or custom search functions might return NULL if they fail, you should wrap your pointer logic in an if statement.

#include <stdio.h>

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

    // BAD: This would cause a crash (Segmentation Fault)
    // printf("%d", *ptr); 

    // GOOD: The safety check
    if (ptr != NULL) {
        printf("The value is: %d\n", *ptr);
    } else {
        printf("Error: The pointer is NULL. Access denied!\n");
    }

    return 0;
}

Why this happens

When you use the * operator, you are telling the CPU: "Go to this specific coordinate in memory." If that coordinate is 0 (which is what NULL usually represents), the CPU hits a hardware wall. It is much better to have your program print a polite error message than to have it vanish instantly because you tried to read from nowhere.

Key takeaway

Always check if a pointer is NULL before using the * or -> operators to ensure your program remains stable.