Handling realloc failure safely
What you'll learn: How to prevent memory leaks by using a temporary pointer when resizing memory with realloc.
The danger of the "Direct Update"
When you need to resize a block of memory, you use realloc. A common mistake is to assign the result directly back to your original pointer, like this: ptr = realloc(ptr, new_size);.
Imagine you are moving your belongings from a small storage unit to a larger one. You hand the key to your current unit to a mover. If the mover comes back and says, "Sorry, there are no larger units available," but then realizes they lost your original key during the search, you are in trouble. You can’t get into your old unit, and you don’t have a new one.
In C, if realloc fails, it returns NULL. If you assign that NULL directly to your only pointer, you lose the address of the original memory block. That memory is now "orphaned"—it's still taking up space, but you have no way to access or free it. This is a classic memory leak.
The "Safety First" pattern
To resize safely, you must use a temporary pointer to hold the result of the attempt. This allows you to check if the move was successful before letting go of your old address.
#include <stdio.h>
#include <stdlib.h>
int main() {
int *data = malloc(5 * sizeof(int));
// ... use the memory ...
// SAFER RESIZING:
// 1. Try to resize using a temporary pointer
int *temp = realloc(data, 1000000 * sizeof(int));
// 2. Check if it worked
if (temp == NULL) {
// Failure! But 'data' is still valid.
// We can clean up or try a different approach.
fprintf(stderr, "Error: Could not resize memory.\n");
free(data);
return 1;
}
// 3. Success! Now it is safe to update the main pointer
data = temp;
// ... continue working ...
free(data);
return 0;
}
Why this matters
By using temp, you create a safety net. If realloc returns NULL, your original data pointer remains untouched, pointing exactly where it did before. You can then decide how to handle the error—perhaps by saving your work and exiting gracefully—rather than crashing because you accidentally wiped out your only map to the data.
Key takeaway
Always assign realloc to a temporary pointer so you don't lose your original memory address if the allocation fails.