Home › C Tutorial › C reallocate memory
C reallocate memory
Resize a block.
realloc grows or shrinks a block and may move it. Store the result in a temporary pointer so you do not lose the original on failure.
Example code
#include <stdio.h>
#include <stdlib.h>
int main() {
int *a = malloc(2 * sizeof(int));
a[0] = 1; a[1] = 2;
int *t = realloc(a, 4 * sizeof(int));
if (t == NULL) { free(a); return 1; }
a = t; a[3] = 4;
printf("%d %d\n", a[1], a[3]);
free(a);
return 0;
}