Skip to content

Grow Without Losing the Original

The Course
•
40 min study

When a growing array is full, it needs a bigger block that still holds the existing elements. realloc(old, bytes) does that in one call. It may extend the block where it is, or it may allocate a new block somewhere else, copy the old contents, and free the old block. You do not get to choose, and you cannot tell in advance. That single fact drives two rules: always use the pointer realloc returns, and treat every old pointer into the block as expired after a successful call.

Failure has its own rule. If realloc cannot provide the new size, it returns NULL and leaves the old block exactly as it was, still allocated and still yours. That is a gift: your collection can report "out of memory" and keep every record it already had. But it is easy to throw that gift away.

Predict and run

Read the program before pressing Run. Write down its output and identify which statements are safe only after success.

Predict before running C
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int *data = malloc(2 * sizeof *data);
    if (data == NULL) { return 1; }
    data[0] = 25; data[1] = 10;
    int *grown = realloc(data, 4 * sizeof *data);
    if (grown == NULL) { free(data); return 1; }
    data = grown;
    data[2] = 15;
    printf("%d\n", data[0] + data[1] + data[2]);
    free(data);
    return 0;
}
Check your prediction
Text
50

realloc keeps 25 and 10 in the first two slots, the program writes 15 into the third, and the sum is 50. The fourth slot exists but was never written, so it must not be read. data = grown and the write to data[2] are safe only after the NULL check. On failure, data still owns the original two elements, so the error path frees it.

The one-line leak

This version looks shorter:

C
data = realloc(data, 4 * sizeof *data);
if (data == NULL) {
    return STATUS_NOMEM;   /* the original block is still allocated, but nothing points to it */
}

When realloc fails, the assignment overwrites the only pointer to the old block with NULL. The block is leaked, and the records in it are gone from the program's point of view. Always receive the result in a temporary, check it, and only then assign it to the owner.

Fix: see the one-line leak happen

On a development machine realloc almost never fails, so this bug hides. The program below wraps realloc in resize, which counts live blocks and fails when fail_next is set. Run it and explain why the count never returns to 0.

Fix: the one-line leak C
#include <stdio.h>
#include <stdlib.h>

static int live = 0;        /* blocks allocated and not yet freed */
static int fail_next = 0;   /* set to 1 to make the next resize fail */

/* realloc that counts blocks and can be told to fail. */
void *resize(void *old, size_t bytes) {
    if (fail_next) { fail_next = 0; return NULL; }
    void *result = realloc(old, bytes);
    if (result != NULL && old == NULL) { ++live; }
    return result;
}

void release(void *block) {
    if (block != NULL) { --live; free(block); }
}

int main(void) {
    int *data = resize(NULL, 2 * sizeof *data);
    if (data == NULL) { return 1; }
    data[0] = 25;
    data[1] = 10;
    fail_next = 1;
    data = resize(data, 4 * sizeof *data);
    if (data == NULL) {
        printf("grow failed, live %d\n", live);
    }
    release(data);
    printf("live at end: %d\n", live);
    return 0;
}
Shell
grow failed, live 1
live at end: 1
Check your fix

After the failed resize, data is NULL, so release(data) does nothing, while the two-element block is still allocated with nobody pointing at it. Receive the result in a temporary, and keep data as the owner on failure:

C
#include <stdio.h>
#include <stdlib.h>

static int live = 0;        /* blocks allocated and not yet freed */
static int fail_next = 0;   /* set to 1 to make the next resize fail */

/* realloc that counts blocks and can be told to fail. */
void *resize(void *old, size_t bytes) {
    if (fail_next) { fail_next = 0; return NULL; }
    void *result = realloc(old, bytes);
    if (result != NULL && old == NULL) { ++live; }
    return result;
}

void release(void *block) {
    if (block != NULL) { --live; free(block); }
}

int main(void) {
    int *data = resize(NULL, 2 * sizeof *data);
    if (data == NULL) { return 1; }
    data[0] = 25;
    data[1] = 10;
    fail_next = 1;
    int *grown = resize(data, 4 * sizeof *grown);
    if (grown == NULL) {
        printf("grow failed, live %d, still %d %d\n", live, data[0], data[1]);
    } else {
        data = grown;
    }
    release(data);
    printf("live at end: %d\n", live);
    return 0;
}
Text
grow failed, live 1, still 25 10
live at end: 0

Commit the pointer and the capacity together

A resize changes two fields: the pointer and the capacity. Both must change on success and neither on failure. A small helper keeps that promise in one place. Note that realloc(NULL, bytes) behaves like malloc(bytes), so the same helper handles the first allocation of an empty array:

A resize helper C
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

typedef enum { STATUS_OK, STATUS_TOO_LARGE, STATUS_NOMEM } Status;
typedef struct { int *data; size_t length; size_t capacity; } List;

Status list_reserve(List *list, size_t capacity) {
    if (capacity <= list->capacity) { return STATUS_OK; }
    if (capacity > SIZE_MAX / sizeof *list->data) { return STATUS_TOO_LARGE; }
    int *grown = realloc(list->data, capacity * sizeof *grown);
    if (grown == NULL) { return STATUS_NOMEM; }
    list->data = grown;
    list->capacity = capacity;
    return STATUS_OK;
}

int main(void) {
    List list = {NULL, 0, 0};
    if (list_reserve(&list, 2) != STATUS_OK) { return 1; }
    list.data[list.length++] = 20;
    list.data[list.length++] = 30;
    Status s = list_reserve(&list, SIZE_MAX);
    printf("huge request: %s, capacity %zu\n", s == STATUS_TOO_LARGE ? "too large" : "?", list.capacity);
    printf("values: %d %d\n", list.data[0], list.data[1]);
    free(list.data);
    return 0;
}
Text
huge request: too large, capacity 2
values: 20 30

The refused request leaves the pointer, the capacity and the elements intact. A real out-of-memory failure takes the same path one line later, and Day 6 shows how to trigger it on demand.

Pointers into the old block expire

A pointer to an element is a borrow from the block. If realloc moves the block, the borrow dangles:

C
int *first = &list.data[0];
list_reserve(&list, 64);   /* may move the block */
printf("%d\n", *first);    /* undefined if it moved */

Even if the block happens not to move, the standard says the old pointer's value is indeterminate after a successful realloc, so even comparing first with list.data is not reliable. Do not try to detect a move. Instead, keep an index across operations that may grow the array, and form a fresh pointer with &list.data[i] when you need one.

The project's analyzer_append faces a subtle version of this. A caller may pass &analyzer.data[0] as the record to append. If append grew the block first and then read the record, it would read through a dangling pointer. So it copies the record into a local variable before resizing.

Do not request zero bytes

What realloc(ptr, 0) does is implementation-defined in C17: it may free the block and return NULL, or return a new small block. C23 goes further and makes it undefined. With the empty-collection policy from Day 2, this course never asks for zero bytes.

Practice

Exercise

Your turn

Copy list_reserve from above and write Status list_push(List *list, int value). When the list is full it reserves a doubled capacity (4 when empty); then it stores the value. Failure leaves the list unchanged. Push 10, 20, 30, 40 and 50 and print the length and capacity after each push, then the values. Expected output: push 10: length 1, capacity 4, then the same pattern for 20, 30 and 40 with lengths 2, 3, 4 and capacity 4, then push 50: length 5, capacity 8, and finally values: 10 20 30 40 50.

Your workspace C
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

typedef enum { STATUS_OK, STATUS_TOO_LARGE, STATUS_NOMEM } Status;
typedef struct { int *data; size_t length; size_t capacity; } List;

/* Copy list_reserve here, then write list_push. */

int main(void) {
    List list = {NULL, 0, 0};
    // Push 10..50, printing length and capacity after each push.
    free(list.data);
    return 0;
}
Hint 1: the idea

list_push should not call realloc itself. It decides the new capacity and lets list_reserve do the checked resize. If the reserve fails, return its status before touching length.

Hint 2: a first step

Before writing anything, ask what a list_push that only stores and counts would do on its very first call: an empty list has capacity 0 and no block at all. So the full check comes first. Write it with the doubled capacity, and decide where the reserve's status is checked so that a failed reserve returns before length changes.

Show one solution
Run the solution C
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

typedef enum { STATUS_OK, STATUS_TOO_LARGE, STATUS_NOMEM } Status;
typedef struct { int *data; size_t length; size_t capacity; } List;

Status list_reserve(List *list, size_t capacity) {
    if (capacity <= list->capacity) { return STATUS_OK; }
    if (capacity > SIZE_MAX / sizeof *list->data) { return STATUS_TOO_LARGE; }
    int *grown = realloc(list->data, capacity * sizeof *grown);
    if (grown == NULL) { return STATUS_NOMEM; }
    list->data = grown;
    list->capacity = capacity;
    return STATUS_OK;
}

Status list_push(List *list, int value) {
    if (list->length == list->capacity) {
        size_t next = list->capacity == 0 ? 4 : list->capacity * 2;
        Status status = list_reserve(list, next);
        if (status != STATUS_OK) { return status; }
    }
    list->data[list->length] = value;
    ++list->length;
    return STATUS_OK;
}

int main(void) {
    List list = {NULL, 0, 0};
    for (int value = 10; value <= 50; value += 10) {
        if (list_push(&list, value) != STATUS_OK) { free(list.data); return 1; }
        printf("push %d: length %zu, capacity %zu\n", value, list.length, list.capacity);
    }
    printf("values:");
    for (size_t i = 0; i < list.length; ++i) { printf(" %d", list.data[i]); }
    printf("\n");
    free(list.data);
    return 0;
}
Text
push 10: length 1, capacity 4
push 20: length 2, capacity 4
push 30: length 3, capacity 4
push 40: length 4, capacity 4
push 50: length 5, capacity 8
values: 10 20 30 40 50

Only two pushes allocate: the first (from NULL to 4) and the fifth (4 to 8). The value is written after the reserve succeeds, and length changes last, so a failed reserve leaves the list exactly as it was. main frees the list's data on both exits, because the list owns it. Next, you will take elements out of the middle of the array without leaving a gap.

Was this article helpful?

Your response is saved on this device.