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

Initializing pointers to NULL

Initializing pointers to NULL

What you'll learn: How to safely set a pointer to a neutral state to prevent your program from crashing or behaving unpredictably.

The danger of "Wild Pointers"

In C, when you create a variable like int x;, it doesn't start at zero. It contains whatever leftover data was sitting in that memory slot—essentially "garbage." The same is true for pointers.

If you declare a pointer using int *ptr; without giving it an address, it becomes a wild pointer. It is pointing to a completely random location in your computer's memory. If you accidentally try to write data to that random address, one of two bad things will happen: your program will crash immediately (a Segmentation Fault), or, even worse, you will silently overwrite data belonging to another part of your program, causing bugs that are nearly impossible to track down.

The "NULL" safety catch

To avoid this, we use a special constant called NULL. Think of NULL as a "No Entry" sign or a grounded wire. It is a way of explicitly telling the computer, "This pointer exists, but it isn't pointing to anything yet."

In C, NULL is actually just the number zero, but we use the word NULL to make it clear that we are dealing with a memory address rather than a math calculation.

How to initialize to NULL

Whenever you create a pointer but aren't ready to point it at a specific variable yet, you should always initialize it to NULL.

#include <stdio.h>

int main() {
    // 1. Initialize the pointer to NULL
    int *ptr = NULL;

    // 2. Later in the code, we can check if it's safe to use
    if (ptr != NULL) {
        printf("The pointer is pointing to: %d\n", *ptr);
    } else {
        printf("The pointer is currently 'empty' and safe.\n");
    }

    // 3. Now we give it a real address
    int score = 95;
    ptr = &score;

    if (ptr != NULL) {
        printf("Now the pointer is safe to dereference: %d\n", *ptr);
    }

    return 0;
}

Why this matters

By setting your pointer to NULL, you turn a "wild" pointer into a "managed" one. If you try to dereference a NULL pointer, the program will still crash, but it will do so predictably and instantly. More importantly, it allows you to use if (ptr != NULL) checks to ensure your code only tries to access memory when it is actually supposed to.

Key takeaway

Always initialize pointers to NULL upon declaration to avoid pointing at random garbage memory.