02. Dynamic Buffer Resizing with realloc()
🟡 Difficulty: Intermediate | Heap Resizing, Temporary Pointer Guards & Capacity Doubling
📖 Definition
The realloc() function in C adjusts the allocated byte size of an existing heap memory block previously returned by malloc() or calloc(). It can expand or shrink the memory block while preserving existing contents up to the minimum of the old and new sizes.
🎯 Why It Is Used
- Dynamic Array Growth: Implementing growable data structures (like dynamic vectors or lists) whose capacity expands automatically as items arrive.
- Memory Efficiency: Trimming over-allocated temporary buffers down to the exact final string/array length.
⚙️ How It Works: In-Place vs Relocated Expansion
When expanding a heap allocation via realloc(ptr, new_size), C's memory manager attempts two strategies:
- In-Place Expansion: If adjacent RAM following the current block is free, the heap manager extends the block bounds and returns the same memory address.
- Relocation: If adjacent RAM is occupied, the manager allocates a new block elsewhere on the heap, copies existing data over, automatically frees the old block, and returns a new memory address.
📝 Syntax
#include <stdlib.h>
// CRITICAL IDIOM: Always assign realloc result to a TEMPORARY pointer first!
int *temp = (int*)realloc(original_ptr, new_size_bytes);
if (temp != NULL) {
original_ptr = temp; // Reallocation succeeded; update pointer
} else {
// Reallocation failed! 'original_ptr' remains VALID and UNTOUCHED!
// Handle error or free(original_ptr);
}
🔀 Capacity Doubling Strategy
To achieve amortized constant time $O(1)$ insertions when appending items to a dynamic array, double the array capacity (capacity = capacity * 2) whenever capacity is exhausted, rather than growing by 1 element on every insertion.
🌱 Beginner Example: Expanding an Array from 3 to 5 Elements
#include <stdio.h>
#include <stdlib.h>
int main(void) {
size_t initial_count = 3;
int *arr = (int*)malloc(initial_count * sizeof(int));
if (arr == NULL) return 1;
for (size_t i = 0; i < initial_count; i++) arr[i] = (int)(i + 1) * 10;
printf("Initial Heap Buffer Address: %p\n", (void*)arr);
// Expand array to hold 5 elements
size_t new_count = 5;
int *temp = (int*)realloc(arr, new_count * sizeof(int));
if (temp == NULL) {
free(arr);
return 1;
}
arr = temp;
arr[3] = 40;
arr[4] = 50;
printf("Resized Heap Buffer Address: %p\n", (void*)arr);
printf("Array Elements: ");
for (size_t i = 0; i < new_count; i++) printf("%d ", arr[i]);
printf("\n");
free(arr);
return 0;
}
🌼 Intermediate Example: Growable Dynamic Vector Pattern
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int *data;
size_t size;
size_t capacity;
} DynamicVector;
void vector_init(DynamicVector *vec) {
vec->size = 0;
vec->capacity = 2; // Initial small capacity
vec->data = (int*)malloc(vec->capacity * sizeof(int));
}
void vector_push_back(DynamicVector *vec, int value) {
if (vec->size >= vec->capacity) {
vec->capacity *= 2; // Amortized O(1) capacity doubling
int *temp = (int*)realloc(vec->data, vec->capacity * sizeof(int));
if (temp == NULL) {
fprintf(stderr, "Vector expansion error!\n");
return;
}
vec->data = temp;
printf("[Vector] Expanded capacity to %zu items\n", vec->capacity);
}
vec->data[vec->size++] = value;
}
void vector_free(DynamicVector *vec) {
free(vec->data);
vec->data = NULL;
vec->size = 0;
vec->capacity = 0;
}
int main(void) {
DynamicVector v;
vector_init(&v);
for (int i = 1; i <= 5; i++) {
vector_push_back(&v, i * 100);
}
printf("Vector Elements: ");
for (size_t i = 0; i < v.size; i++) printf("%d ", v.data[i]);
printf("\n");
vector_free(&v);
return 0;
}
🌲 Advanced Example: Shrinking Excess Heap Space
#include <stdio.h>
#include <stdlib.h>
int main(void) {
// Allocate large over-dimensioned buffer
int *large_buf = (int*)malloc(100 * sizeof(int));
if (large_buf == NULL) return 1;
// Use only first 5 elements
for (int i = 0; i < 5; i++) large_buf[i] = i + 1;
printf("Pre-shrink Capacity : 100 ints\n");
// Trim allocation to exact 5 elements
int *trimmed = (int*)realloc(large_buf, 5 * sizeof(int));
if (trimmed != NULL) {
large_buf = trimmed;
printf("Post-shrink Capacity: 5 ints (Memory reclaimed!)\n");
}
free(large_buf);
return 0;
}
🔍 Line-by-Line Explanation
int *temp = (int*)realloc(arr, new_size);: Stores the return pointer intemp. If reallocation fails and returnsNULL,arris still valid and not leaked.vec->capacity *= 2;: Implements the exponential capacity doubling strategy for dynamic vector lists.realloc(large_buf, 5 * sizeof(int));: Reclaims unused heap bytes by shrinking the block size.
💻 Expected Terminal Output
Initial Heap Buffer Address: 0x5601a21042a0
Resized Heap Buffer Address: 0x5601a21042a0
Array Elements: 10 20 30 40 50
[Vector] Expanded capacity to 4 items
[Vector] Expanded capacity to 8 items
Vector Elements: 100 200 300 400 500
Pre-shrink Capacity : 100 ints
Post-shrink Capacity: 5 ints (Memory reclaimed!)
⚠️ Common Mistakes & Pitfalls
- Direct Re-assignment Trap (
ptr = realloc(ptr, new_size)): Ifrealloc()fails and returnsNULL, overwritingptrwithNULLpermanently loses the address of the original heap block, causing an unrecoverable Memory Leak! - Using Old Pointer Address After Relocation: If
realloc()moves the block to a new address, using the oldptraddress leads to Use-After-Free memory corruption.
📌 Important Rules & Limitations
- Always store
realloc()results in a temporary pointer first. realloc(NULL, size)behaves identically tomalloc(size).realloc(ptr, 0)is implementation-defined; always callfree(ptr)explicitly instead of reallocating to size 0.
🌐 Multilingual Explanation: English
realloc() resizes existing heap blocks, expanding or relocating as needed. Always store the return value in a temporary pointer to prevent memory leaks if allocation fails.
🌐 Multilingual Explanation: Hindi (Roman Script)
realloc() heap memory ka size badhane ya ghatane ke liye use hota hai. realloc() ke result ko hamesha temp pointer mein rakhein taaki failure ke case mein purana data leak na ho.
🌐 Multilingual Explanation: Marathi (Roman Script)
realloc() mughal heap memory resize karta yete. Return pointer nehamhi temp variable madhye store kara.
❓ Practice Questions
- Why is writing
ptr = realloc(ptr, new_size)considered a severe memory leak anti-pattern? - What happens if
realloc()expands a buffer in-place vs when it relocates the buffer? - How does dynamic vector capacity doubling maintain amortized $O(1)$ append time?
🚀 Practical Coding Challenge
Write a C program named dynamic_string_builder.c that reads characters one by one from stdin and uses realloc() with capacity doubling to build a dynamic string of arbitrary length.
🧭 Navigation & Breadcrumbs
← Previous: 01. Heap Allocation | Module 12 Guide | Next: 03. Memory Leaks & Sanitizers →