Course contentsShow
← C
Lesson 539 of 1,2198. Memory ManagementFree lesson

Checking for NULL return values

Checking for NULL return values

What you'll learn: How to verify that your memory requests were successful to prevent your program from crashing.

The "No Vacancy" Sign

Imagine you call a hotel to book a room. You expect them to give you a room number, but there is always a chance the hotel is completely full. If you simply show up and try to walk into "Room 0" without checking if your booking was confirmed, you’ll be stopped at the door—or worse.

In C, the malloc function acts like that hotel clerk. When you ask for memory, it usually gives you a valid address. However, if the computer is out of RAM, malloc can’t give you what you asked for. Instead of an address, it returns NULL.

Why Checking Matters

A NULL pointer is essentially a pointer to nowhere (address 0). If you try to write data to a NULL pointer—a mistake called "dereferencing a null pointer"—your program will immediately crash with a "Segmentation Fault."

To write professional, stable code, you must treat malloc as a request that might fail. You should never assume the memory is there until you have checked it with an if statement.

The Standard Safety Check

Every time you use malloc, follow it immediately with a check. If the pointer is NULL, you should handle the error (usually by printing a message and exiting the program) rather than trying to use the memory.

#include <stdio.h>
#include <stdlib.h>

int main() {
    // Requesting space for 1000 integers
    int *buffer = malloc(1000 * sizeof(int));

    // The Essential Check
    if (buffer == NULL) {
        printf("Error: Could not allocate memory!\n");
        return 1; // Exit the program with an error code
    }

    // If we reach this point, buffer is safe to use
    buffer[0] = 42;
    printf("Memory allocated successfully. Value: %d\n", buffer[0]);

    free(buffer);
    return 0;
}

By adding these three lines of code after every allocation, you build a "safety net." It ensures that if the computer runs out of resources, your program shuts down gracefully with an explanation rather than collapsing unexpectedly.

Key takeaway

Always verify that a pointer returned by malloc is not NULL before attempting to use it.