Course contentsShow
← C
Lesson 622 of 1,2199. Structures and UnionsFree lesson

The importance of NULL checks for struct pointers

The importance of NULL checks for struct pointers

What you'll learn: You will learn why checking if a structure pointer is valid before accessing its members is the best way to prevent your program from crashing.

The "Empty Envelope" problem

Think of a pointer to a struct like a mailing address written on an envelope. Inside that "house" (the struct) are several rooms (the members, like id or price). When you use the arrow operator (->), you are telling the computer: "Go to this address and look inside the room named 'price'."

But what if the envelope is empty? In C, a pointer that doesn't point to anything is often set to NULL. If you try to follow a NULL pointer, you are essentially telling the computer to go to "Address Nowhere." The computer gets confused, panics, and shuts down your program immediately. This is the dreaded "Segmentation Fault."

Defending your code

Because structures often hold critical data, you should never assume a pointer is valid, especially if it was returned by a function or a memory allocation call. A simple if statement acts as a safety gate. By checking if (ptr != NULL), you ensure the "house" actually exists before you try to walk through the front door.

Implementation in C

Here is how you safely handle a pointer to a User structure:

#include <stdio.h>

struct User {
    int id;
    float balance;
};

void printUserBalance(struct User *ptr) {
    // The Safety Gate: check if the pointer is NULL first
    if (ptr == NULL) {
        printf("Error: No user data provided.\n");
        return;
    }

    // Now it is safe to use the arrow operator
    printf("User ID %d has a balance of $%.2f\n", ptr->id, ptr->balance);
}

int main() {
    struct User *myUser = NULL; // Currently points to nothing
    
    // This call is safe because our function checks for NULL
    printUserBalance(myUser); 
    
    return 0;
}

Why it matters

In professional software, functions often fail for reasons outside your control—like a database being disconnected or a computer running out of memory. These functions will often return NULL to signal that something went wrong. If you don't check for that NULL value before using ->, your program will crash instead of handling the error gracefully.

Key takeaway

Always verify that a struct pointer is not NULL before using the arrow operator to access its members.