Resizing blocks with realloc
What you'll learn: How to grow or shrink an existing heap memory allocation without manually copying data.
The "Expanding Suitcase" Analogy
Imagine you are packing for a trip. You pick a small suitcase (malloc), but halfway through packing, you realize you need to bring three more pairs of shoes. In the physical world, you’d have to find a bigger suitcase and move everything over piece by piece.
In C, the realloc function acts like a magic suitcase that can stretch. You tell it which pointer you are using and how much space you now need. C will try to grow the memory block right where it sits. If there isn't enough room because other data is in the way, C will automatically find a new, larger spot, move your data for you, and give you the new address.
Using realloc Safely
The syntax for realloc is: void* realloc(void* ptr, size_t new_size);.
There is one major "gotcha": if realloc fails (because the computer is out of memory), it returns NULL. If you assign that NULL directly to your original pointer, you lose the address of your old data, creating a memory leak. Always use a temporary pointer to check the result first.
#include <stdio.h>
#include <stdlib.h>
int main() {
// 1. Start with space for 2 integers
int *arr = malloc(2 * sizeof(int));
arr[0] = 10;
arr[1] = 20;
// 2. We need space for 4 integers now
// Use a temporary pointer to be safe!
int *temp = realloc(arr, 4 * sizeof(int));
if (temp != NULL) {
arr = temp; // Success! arr now points to the new, larger space
arr[2] = 30;
arr[3] = 40;
} else {
// Handle error: original 'arr' is still valid and unchanged
free(arr);
return 1;
}
free(arr);
return 0;
}
Why not just malloc again?
You could use malloc to get a bigger block, use a for loop to copy the old data, and then free the old block. However, realloc is more efficient. If there is enough empty space immediately following your current block, realloc simply updates the heap's bookkeeping to say "this block is now longer," avoiding the expensive process of copying data entirely.
Key takeaway
Use realloc to resize existing memory blocks, but always assign the result to a temporary pointer first to prevent losing your data if the allocation fails.