Example 1 — Grow an array from three to six elements
Use a temporary pointer so a failure cannot leak the original block.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *a = malloc(3 * sizeof *a);
if (!a) return 1;
for (int i = 0; i < 3; i++) a[i] = i + 1;
int *tmp = realloc(a, 6 * sizeof *a);
if (!tmp) { free(a); return 1; }
a = tmp;
for (int i = 3; i < 6; i++) a[i] = i + 1;
for (int i = 0; i < 6; i++) printf("%d ", a[i]);
printf("\n");
free(a);
return 0;
} How It Works
- The first three values are preserved by
realloc. - The temporary pointer protects
aif the call fails. - The new slots are uninitialized, so the loop fills them.
