CKTIS / C
realloc — resizing an allocation
`realloc` resizes a dynamic allocation. Use a temporary pointer and check the result before replacing the existing pointer.
Version: C23; repository compiler flag, production runtime not attested
Syntax
#include <stdlib.h>
void *realloc(void *ptr, size_t size);realloc from <stdlib.h> takes a byte size. It preserves the initial bytes through the smaller of the old and new sizes; added bytes have unspecified values.
Success ends the old object's lifetime, even at the same address. Use the returned pointer; rebuild element pointers. On failure for a positive size, the result is NULL and the old allocation remains unchanged. Assigning the result directly to p can therefore lose the allocation.
For NULL, the function behaves like malloc. Otherwise, the start of a live allocation is required, and zero size means undefined behavior in C23. Use free for deallocation. For variable n, check n <= SIZE_MAX / sizeof *p before multiplication (<stdint.h>).
The example grows an array and initializes the new element. The repository's C23 flag does not attest production runtime conformance.
Examples
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int *p = malloc(2 * sizeof *p);
if (p == NULL) {
return EXIT_FAILURE;
}
p[0] = 10;
p[1] = 20;
int *tmp = realloc(p, 3 * sizeof *p);
if (tmp == NULL) {
free(p);
return EXIT_FAILURE;
}
p = tmp;
p[2] = 30;
printf("%d %d %d\n", p[0], p[1], p[2]);
free(p);
return EXIT_SUCCESS;
}Result
10 20 30
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.