Lesson 3 of 5
realloc - Growing Dynamic Buffers
`realloc(ptr, new_size)` resizes a heap allocation. It may move the block to a new address (returning a new pointer) or extend it in-place. **The critical mistake**: assigning `realloc`'s return value directly to the original pointer - if `realloc` fails it returns `NULL` while the original block is still allocated, causing a memory leak.
realloc - Safe Pattern & Dynamic Array Growth
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* ── Safe realloc wrapper - NEVER realloc directly ──────── */
/* WRONG - loses original pointer on failure:
arr = realloc(arr, new_size); ← if returns NULL: leak! */
void *safe_realloc(void *ptr, size_t new_size) {
void *new_ptr = realloc(ptr, new_size);
if (new_ptr == NULL) {
/* Original 'ptr' is STILL valid! Caller must free it. */
fprintf(stderr, "realloc(%zu) failed
", new_size);
return NULL;
}
return new_ptr;
}
/* ── Dynamic array with automatic growth ──────────────────── */
typedef struct {
int *data;
size_t size; /* current number of elements */
size_t capacity; /* allocated slots */
} DynArray;
void dynarray_init(DynArray *da) {
da->data = NULL;
da->size = 0;
da->capacity = 0;
}
int dynarray_push(DynArray *da, int value) {
if (da->size == da->capacity) {
/* Double capacity (amortized O(1) push) */
size_t new_cap = da->capacity == 0 ? 4 : da->capacity * 2;
int *tmp = safe_realloc(da->data, new_cap * sizeof(int));
if (tmp == NULL) {
return -1; /* fail - da->data still valid */
}
da->data = tmp;
da->capacity = new_cap;
}
da->data[da->size++] = value;
return 0;
}
void dynarray_free(DynArray *da) {
free(da->data);
da->data = NULL;
da->size = da->capacity = 0;
}
int main(void) {
DynArray da;
dynarray_init(&da);
for (int i = 1; i <= 20; i++) {
if (dynarray_push(&da, i * i) != 0) {
fprintf(stderr, "push failed at i=%d
", i);
dynarray_free(&da);
return 1;
}
}
printf("size=%zu capacity=%zu
", da.size, da.capacity);
printf("First 5: ");
for (size_t i = 0; i < 5 && i < da.size; i++) printf("%d ", da.data[i]);
printf("
");
dynarray_free(&da);
return 0;
}Common Mistakes
- Storing `realloc`'s return directly back - `arr = realloc(arr, new_size)` → if realloc fails and returns NULL, `arr` is now NULL and you've lost the only pointer to the original block. Always use a temporary: `tmp = realloc(arr, n); if (tmp) arr = tmp; else free(arr);`.
- Passing a non-malloc'd pointer to realloc - `realloc` only works on heap-allocated pointers. Passing a stack pointer or a misaligned pointer is undefined behaviour.
- Not updating both size and capacity - when the realloc succeeds, update `capacity` to the new value. Forgetting this causes realloc on every subsequent push (O(n²) behaviour).
Tip
Tip
Practice realloc Growing Dynamic Buffers in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
realloc resizes buffers in-place or relocates data, returning a pointer to the new memory block
Practice Task
Note
Practice Task - (1) Write a working example of realloc Growing Dynamic Buffers from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with realloc Growing Dynamic Buffers is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready c code.
Key Takeaways
- `realloc(ptr, new_size)` resizes a heap allocation.
- Storing `realloc`'s return directly back - `arr = realloc(arr, new_size)` → if realloc fails and returns NULL, `arr` is now NULL and you've lost the only pointer to the original block. Always use a temporary: `tmp = realloc(arr, n); if (tmp) arr = tmp; else free(arr);`.
- Passing a non-malloc'd pointer to realloc - `realloc` only works on heap-allocated pointers. Passing a stack pointer or a misaligned pointer is undefined behaviour.
- Not updating both size and capacity - when the realloc succeeds, update `capacity` to the new value. Forgetting this causes realloc on every subsequent push (O(n²) behaviour).
Finished this lesson?