Library contents

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

  1. Start with An allocated array with one integer 2
  2. Do this Grow it to hold two integers
  3. Result First value still 2 on success
Successful growth preserves the previous bytes. Save the returned pointer separately until success is known.

Syntax

C 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.

From the programitems[0] = 5
Result12
lesson.c
#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;
}
Output
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

Advertisements

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?

Given6 occupied + 4 incoming
Worked result10

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?

Given10 occupied + 8 incoming
Worked result18