Reallocating to a smaller size
What you'll learn: How to use realloc to shrink an existing memory block to save space without losing your data.
Trimming the excess
Imagine you are packing for a trip. You initially grab a massive suitcase because you aren't sure how much gear you’ll need. Once you’ve finished packing, you realize your clothes only take up a third of the space. To save room in the car, you transfer everything into a smaller, snugger bag.
In C, realloc allows you to do exactly this with memory. While we often use realloc to make arrays bigger, it is equally useful for shrinking them. If you allocated space for 1,000 integers but realized you only used 50, you can "trim" that memory to free up the unused portion for the rest of your system.
How it works
When you pass a smaller size to realloc, the computer usually keeps the memory block at its current address but marks the trailing end as "free." Your data at the beginning of the block stays exactly where it is, undisturbed.
#include <stdio.h>
#include <stdlib.h>
int main() {
// 1. Allocate a large block (100 integers)
int *numbers = malloc(100 * sizeof(int));
// 2. Use only the first 2 slots
numbers[0] = 10;
numbers[1] = 20;
// 3. Shrink the block to only hold 2 integers
int *temp = realloc(numbers, 2 * sizeof(int));
if (temp != NULL) {
numbers = temp;
printf("Value 1: %d, Value 2: %d\n", numbers[0], numbers[1]);
}
free(numbers);
return 0;
}
Why bother shrinking?
You might wonder: "If I already have the memory, why give it back?"
In small programs, it doesn't matter much. However, in long-running applications (like a web server or a game), holding onto large "ghost" buffers you aren't using is wasteful. Shrinking memory is an act of being a good neighbor to other processes. Just remember that once you shrink a block, you must never try to access the "trimmed" index positions again; that memory is no longer yours, and touching it will cause a crash.
Key takeaway
Use realloc with a smaller size to release unused memory back to the system while keeping your existing data intact.