Resizing blocks with realloc
What you'll learn: How to dynamically grow or shrink an existing memory allocation when your data needs change.
Imagine you are hosting a dinner party. You initially set the table for four people using malloc. Suddenly, three more friends show up. Instead of throwing away the entire table and starting over in a different room, you’d ideally like to just "extend" the table to fit the new guests. In C, the realloc function acts as that table extension.
Why use realloc?
Programs are rarely static. You might start by reading a file into a buffer of 100 bytes, only to realize the file is actually 500 bytes long. If you used a fixed array, you’d be stuck. If you used malloc, you’d have to manually allocate a new block, copy the old data over, and free the old block. realloc automates this entire process in one line.
How it works
The realloc function takes two arguments: the pointer to your current memory block and the new total size you want.
- Expansion: If there is enough free space immediately following your current block, C simply extends your boundary.
- Relocation: If the current spot is "landlocked" by other data, C finds a brand-new, larger spot elsewhere, copies your old data there, frees the old memory, and gives you a pointer to the new location.
- Shrinking: If you ask for a smaller size, C simply trims the end of the block.
A concrete example
Here is how you safely expand an integer array:
#include <stdio.h>
#include <stdlib.h>
int main() {
// Start with space for 2 integers
int *numbers = malloc(2 * sizeof(int));
numbers[0] = 10;
numbers[1] = 20;
// We need room for one more!
// Always assign to a temporary pointer first for safety
int *temp = realloc(numbers, 3 * sizeof(int));
if (temp != NULL) {
numbers = temp;
numbers[2] = 30; // Now we can use the new slot
}
printf("Third number: %d\n", numbers[2]);
free(numbers);
return 0;
}
A note on safety
Always assign the result of realloc to a temporary pointer. If realloc fails (because the system is out of memory), it returns NULL. If you wrote numbers = realloc(numbers, size), and it failed, you would lose the pointer to your original data, creating a memory leak. By using a temp pointer, you ensure that even if the expansion fails, you still have access to your original data.
Key takeaway
Use realloc to resize existing memory blocks dynamically, but always use a temporary pointer to handle potential allocation failures.