Validating function arguments with NULL checks
What you'll learn: How to prevent program crashes by ensuring pointer arguments point to valid memory before using them.
The "Empty Box" problem
Imagine you are a chef, and an assistant hands you a box labeled "Secret Spices." You don't look inside; you just flip the box over to pour it into the pot. If the box was actually empty, nothing happens. But in C, if you try to "pour out" (dereference) a pointer that points to NULL, the program doesn't just stay empty—it crashes instantly.
A NULL pointer is the equivalent of an empty box. Defensive programming is the habit of checking if the box contains something before you try to cook with it.
Why check for NULL?
In C, functions often receive pointers to arrays or structures. If another part of your code fails to allocate memory or passes an uninitialized pointer to your function, your program will trigger a "Segmentation Fault." By adding a simple check at the very beginning of your function, you can handle the error gracefully instead of letting the program die.
Coding the safety net
When you write a function that accepts a pointer, the first few lines should act like a security guard.
#include <stdio.h>
void print_uppercase(char *message) {
// 1. The Defensive Check
if (message == NULL) {
printf("Error: Received a null pointer. Operation aborted.\n");
return;
}
// 2. The Actual Work
// This is now safe to do because we verified 'message' exists
printf("Message: %s\n", message);
}
int main() {
char *my_str = "Hello World";
char *empty_str = NULL;
print_uppercase(my_str); // Works fine
print_uppercase(empty_str); // Caught by our check!
return 0;
}
In the example above, if we didn't have the if (message == NULL) check, the printf function would try to read memory at address zero, causing a crash. By returning early, we keep the program running.
When to use this
You don't need to check every single variable, but you should check pointers that come from "outside"—such as user input, file handles, or memory allocated with malloc. It makes your functions "bulletproof," ensuring that even if the rest of the program makes a mistake, your function won't be the one to break everything.
Key takeaway
Always verify that a pointer is not NULL before dereferencing it to ensure your program fails gracefully rather than crashing.