Lesson 38 of 50 · c
Dynamic Memory – Reallocating Arrays
Duration: 10 mins
realloc changes the size of an existing allocation while preserving its content.
int *arr = malloc(5 * sizeof *arr);
/* ... fill ... */
arr = realloc(arr, 10 * sizeof *arr); // grow to 10 elements
If the block cannot be enlarged in place, realloc allocates a new block, copies the old data, frees the old block, and returns the new pointer. Always assign to a temporary variable first to avoid losing the original pointer on failure.
📚 Example: Growing an Integer Buffer
#include <stdio.h>
#include <stdlib.h>
int main(void) {
size_t cap = 4, used = 0;
int *buf = malloc(cap * sizeof *buf);
if (!buf) return 1;
for (int i = 0; i < 12; ++i) {
if (used == cap) {
size_t newCap = cap * 2;
int *tmp = realloc(buf, newCap * sizeof *tmp);
if (!tmp) { free(buf); return 1; }
buf = tmp; cap = newCap;
}
buf[used++] = i * i;
}
for (size_t i = 0; i < used; ++i) printf("%d ", buf[i]);
printf("\n");
free(buf);
return 0;
}