typestar

realloc in C

Resizing a heap allocation, growing an array.

#include <stdlib.h>

int *grow(int *items, int old_n, int new_n) {
    int *bigger = realloc(items, new_n * sizeof(int));
    if (bigger == NULL) {
        free(items);
        return NULL;
    }
    for (int i = old_n; i < new_n; i++)
        bigger[i] = 0;
    return bigger;
}

How it works

  1. realloc returns a possibly-moved larger block.
  2. On failure the old block is freed to avoid a leak.
  3. New slots are zeroed before use.

Keywords and builtins used here

The run, in numbers

Lines
12
Characters to type
235
Tokens
77
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 49 seconds.

Type this snippet

Step 3 of 5 in Dynamic memory, step 12 of 25 in Pointers & memory.

← Previous Next →