Skip to content

Count and Capacity

The Course
•
35 min study

Yesterday's IntArray had exactly as many slots as elements. That is fine for data whose size is known once, but the analyzer receives records one line at a time. If the array grows by exactly one slot per record, every append has to request a bigger block and copy every existing element into it. For 1024 records that is more than half a million element copies. The fix is to reserve more space than you need right now, and to track two numbers: how many elements are active, and how many fit.

A growing array has three fields: data, length and capacity. The invariant, a fact that must be true whenever no function is in the middle of changing the array, is length <= capacity. Only the elements at indexes 0 up to length - 1 are active. The slots after them are reserved space and hold no records, so reading them is a bug even though the memory exists.

Predict and run

Read the program before pressing Run. Write down its output and explain each number.

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

int main(void) {
    size_t length = 2;
    size_t capacity = 4;
    printf("Active: %zu, spare: %zu\n", length, capacity - length);
    return 0;
}
Check your prediction
Text
Active: 2, spare: 2

capacity - length is the number of appends that need no new allocation. The subtraction is only safe because the invariant guarantees length <= capacity. If some bug made length 5, the unsigned result would wrap to a huge "spare" count, and the next append would write past the block. Every function that changes these fields is responsible for keeping the invariant true when it returns.

Why doubling beats growing by one

Count the work. Each time the array grows, realloc may move the block and copy every active element. This program counts those copies for 1024 appends under two policies, without allocating anything:

Count the copies C
#include <stdio.h>
#include <stddef.h>

static void simulate(const char *name, int doubling) {
    size_t length = 0, capacity = 0, resizes = 0, copies = 0;
    for (size_t record = 0; record < 1024; ++record) {
        if (length == capacity) {
            copies += length;
            capacity = doubling ? (capacity == 0 ? 4 : capacity * 2) : capacity + 1;
            ++resizes;
        }
        ++length;
    }
    printf("%s: %zu resizes, %zu copies\n", name, resizes, copies);
}

int main(void) {
    simulate("grow by one", 0);
    simulate("double from 4", 1);
    return 0;
}
Text
grow by one: 1024 resizes, 523776 copies
double from 4: 9 resizes, 1020 copies

With doubling, the copies add up to fewer than one per element, because each resize pays for as many future appends as the array already holds. The cost is spare space: right after a resize, up to half the capacity is unused. That trade is almost always worth it, and it is what the project does.

Put a ceiling on growth

Unbounded doubling has two problems. capacity * 2 can itself overflow once the capacity passes SIZE_MAX / 2. More practically, a program that accepts any amount of input can be made to use any amount of memory. The analyzer documents a limit of 1024 records, which also keeps the report totals within the range of long (Day 1). The next capacity is doubled and then clamped to the limit:

C
size_t next = capacity == 0 ? 4 : capacity * 2;
if (next > limit) { next = limit; }

Because the limit is small, capacity * 2 cannot overflow here. A general-purpose array without such a limit must check capacity > SIZE_MAX / 2 before doubling, and still check the byte count from Day 2 before allocating.

Removing does not shrink

When a record is removed, length drops and capacity stays the same. The freed slot becomes spare space for the next append. Shrinking the block after every removal would bring back the copying cost you just avoided, and a later append would immediately grow it again. Programs that do shrink usually wait until the array is much emptier, such as a quarter full.

Practice

Exercise

Your turn

Write Status capacity_for_append(size_t length, size_t capacity, size_t limit, size_t *out). It answers: "what capacity is needed to append one element?" If there is room, store the current capacity. If length >= limit, return STATUS_FULL and leave *out unchanged. Otherwise store the doubled capacity (4 when it was 0), clamped to limit. The starter must print, one per line: (0, 0, 1024): ok -> 4, (2, 4, 1024): ok -> 4, (4, 4, 1024): ok -> 8, (600, 600, 1024): ok -> 1024, (1024, 1024, 1024): full, (0, 0, 3): ok -> 3.

Your workspace C
#include <stdio.h>
#include <stddef.h>

typedef enum { STATUS_OK, STATUS_FULL } Status;

/* Write capacity_for_append here. */

static void show(size_t length, size_t capacity, size_t limit) {
    size_t out = 0;
    if (capacity_for_append(length, capacity, limit, &out) == STATUS_OK) {
        printf("(%zu, %zu, %zu): ok -> %zu\n", length, capacity, limit, out);
    } else {
        printf("(%zu, %zu, %zu): full\n", length, capacity, limit);
    }
}

int main(void) {
    show(0, 0, 1024);
    show(2, 4, 1024);
    show(4, 4, 1024);
    show(600, 600, 1024);
    show(1024, 1024, 1024);
    show(0, 0, 3);
    return 0;
}
Hint 1: the idea

There are three situations: room already exists, the limit is reached, or growth is needed. Check them in that order, and remember that length < capacity means room.

Hint 2: a first step

Write the three situations as three empty branches first, in the hint's order, each returning a status but storing nothing. Then fill them one at a time, running after each; the clamp is the last thing to add, and only the (600, 600, 1024) and (0, 0, 3) lines depend on it.

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

typedef enum { STATUS_OK, STATUS_FULL } Status;

Status capacity_for_append(size_t length, size_t capacity, size_t limit, size_t *out) {
    if (length < capacity) {
        *out = capacity;
        return STATUS_OK;
    }
    if (length >= limit) { return STATUS_FULL; }
    size_t next = capacity == 0 ? 4 : capacity * 2;
    if (next > limit) { next = limit; }
    *out = next;
    return STATUS_OK;
}

static void show(size_t length, size_t capacity, size_t limit) {
    size_t out = 0;
    if (capacity_for_append(length, capacity, limit, &out) == STATUS_OK) {
        printf("(%zu, %zu, %zu): ok -> %zu\n", length, capacity, limit, out);
    } else {
        printf("(%zu, %zu, %zu): full\n", length, capacity, limit);
    }
}

int main(void) {
    show(0, 0, 1024);
    show(2, 4, 1024);
    show(4, 4, 1024);
    show(600, 600, 1024);
    show(1024, 1024, 1024);
    show(0, 0, 3);
    return 0;
}
Text
(0, 0, 1024): ok -> 4
(2, 4, 1024): ok -> 4
(4, 4, 1024): ok -> 8
(600, 600, 1024): ok -> 1024
(1024, 1024, 1024): full
(0, 0, 3): ok -> 3

The clamp handles both the case where doubling overshoots (600 to 1024 instead of 1200) and the case where even the first capacity is above the limit (3 instead of 4). Because next is never above limit, the new capacity cannot exceed it and the full check is the only way to refuse. Next, you will use this capacity to actually resize a block with realloc, without losing the old one if that fails.

Was this article helpful?

Your response is saved on this device.