C realloc and free
realloc resizes an allocation and preserves the prefix that fits in the new block. The address of the block may change.
A simple example
realloc and free
- Start with An allocated array with one integer 2
- Do this Grow it to hold two integers
- Result First value still 2 on success
Syntax
int *new_items = realloc(items, count * sizeof *items)
Run this example in C
Save the program as lesson.c. Use C17 and a Unix-style shell.
cc -std=c17 -Wall -Wextra lesson.c -lm -o lesson
./lesson
Grow a readings buffer safely
A batch can contain enough readings, or large enough values, to exceed a simple implementation's assumptions. Select a safe representation or comparison before combining, storing or ordering those inputs.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *items = malloc(sizeof *items);
if (!items) return 1;
items[0] = 5;
int *grown = realloc(items, 2 * sizeof *items);
if (!grown) {
free(items);
return 1;
}
items = grown;
items[1] = 7;
printf("%d\n", items[0] + items[1]);
free(items);
return 0;
}
12
For a nonzero request, failure leaves the original allocation available. Keep the old pointer until success. For a count supplied at runtime, check for multiplication overflow before computing the byte size.
Open Group function reference for realloc and free
Grow a studio reading buffer
The sensor desk has six one-byte samples and expects four more. Plan enough storage for both batches before filling the buffer. What minimum capacity, in item slots, should be requested?
Reserve a class roster buffer
A registration desk has ten records and expects a group of eight. Plan enough storage for both batches before filling the buffer. What minimum capacity, in item slots, should be requested?