Course contentsShow
← Computer Science
Lesson 316 of 2,8728. Linked Data StructuresFree lesson

NULL Pointers and Defensive Programming

Recognizing null pointers as invalid addresses and checking for null before dereferencing to prevent crashes.

NULL Pointers and Defensive Programming

What you'll learn: How to recognize NULL pointers as invalid addresses and check for them before dereferencing to prevent program crashes.


What is a NULL Pointer?

A NULL pointer is a special pointer value that doesn't point to any valid memory location. Think of it like having a slip of paper that says "there is no address here" instead of containing an actual street address. In C and similar languages, NULL (often represented as 0 or a special constant) indicates that a pointer is intentionally pointing to nothing.

Why NULL Pointers Matter

When you declare a pointer but don't initialize it, or when certain operations fail (like memory allocation), the pointer may be NULL. If you try to dereference a NULL pointer—that is, access the memory it "points to"—you're attempting to read from or write to an invalid location. This causes your program to crash with errors like "segmentation fault" or "access violation."

Defensive Programming: Check Before You Dereference

Before using the dereference operator (*) on any pointer, always check if it's NULL first. This is called defensive programming—protecting your code from unexpected situations.

int *ptr = NULL;  // explicitly set to NULL

// DANGEROUS - would crash:
// int value = *ptr;

// SAFE - check first:
if (ptr != NULL) {
    int value = *ptr;  // only dereference if valid
} else {
    // handle the error gracefully
}

This simple check prevents crashes and makes your program more robust. It's like checking whether that address slip actually contains an address before driving to it.

Key Takeaway: Always check if a pointer is NULL before dereferencing it—this simple defensive practice prevents crashes and makes your code safer and more reliable.