Skip to content

Respect Storage Capacity

The Course
•
32 min study

The report keeps at most eight sessions in an array declared with eight elements. The input, though, can contain any number of valid lines. What should happen to the ninth? Writing it to sessions[8] is past the end of the array, undefined behavior that can silently overwrite whatever lives next to it in memory, such as the count itself. The safe answer is a function that refuses: it checks for room before storing, and when the collection is full it reports failure and changes nothing. The caller then decides what a refusal means; in the project, it is one more rejected line.

Predict and run

Three values are offered to a two-slot array. Predict all four numbers.

Predict before running C
#include <stdio.h>

int append(int values[], int *count, int value) {
    if (*count >= 2) {
        return 0;
    }
    values[*count] = value;
    (*count)++;
    return 1;
}

int main(void) {
    int values[2] = {0};
    int count = 0;
    int first = append(values, &count, 25);
    int second = append(values, &count, 10);
    int third = append(values, &count, 30);
    printf("%d %d %d: %d\n", first, second, third, count);
    return 0;
}
Check your prediction
Text
1 1 0: 2

The first two calls stored at indexes 0 and 1 and increased the count each time. On the third call the count was already 2, the capacity, so the function returned 0 before indexing. The third value went nowhere, the stored values are still 25 and 10, and the count is still 2.

Count is the next free index

The pattern rests on one fact: when count elements are in use, they occupy indexes 0 through count - 1, so count is exactly the index of the first free slot. Storing at values[*count] and then increasing the count keeps that true after every call. Both steps must happen together, and only after the checks:

  1. Check that there is room: the count is less than the capacity.
  2. Store at index count.
  3. Increase the count, exactly once.

If the store happens and the increment is forgotten, the next call overwrites the same slot. If the increment happens without a store, the report counts a slot full of leftover data.

Defend against impossible inputs

The two-slot append trusts its caller completely. The project's add_session checks more, because a public helper should not cause undefined behavior even when misused:

C
if (sessions == NULL || count == NULL || *count < 0 ||
    *count >= SESSION_CAPACITY || minutes < 1 || minutes > MAX_MINUTES) {
    return 0;
}

Each test guards a specific failure. A NULL array or count would be dereferenced. A negative count would index before the start of the array, which is just as undefined as indexing past its end. A full collection would be overrun. An out-of-range duration would put bad data into the report. The order matters as well: count == NULL is tested before *count is read, and short-circuiting guarantees the read never happens for a null pointer.

(*count)++ is not *count++

The count belongs to the caller, so the function receives int *count and must increase the int it points to. The parentheses in (*count)++ matter. Postfix ++ binds more tightly than *, so *count++ means *(count++): move the pointer to the next int, then read the old target and discard it. The caller's count never changes.

The parentheses decide what grows C
#include <stdio.h>

void add_one(int *count) {
    (*count)++;
}

int main(void) {
    int count = 3;
    add_one(&count);
    add_one(&count);
    printf("%d\n", count);
    return 0;
}
Text
5

Write *count++ in add_one and a local build with -Wall -Werror stops with a warning that the result of the expression is unused. The browser editor builds without warning flags, so here it runs and moves the pointer instead of the count. The warning is lucky when you get it. Writing *count += 1 is a clear alternative that cannot be misread.

Practice

Exercise

Your turn

Write int append_valid(int values[], int *count, int capacity, int value). It returns 0 without changing anything for a NULL pointer, a negative count, a full collection or a value outside 1 through 180; otherwise it stores, increments and returns 1. With a three-slot array, assert that 0 is rejected with the count still 0, then that 25, 10 and 40 are stored, that a fourth value is refused with the count still 3, and that a negative count is refused. Print:

Text
Stored 25 10 40, count 3
Capacity checks passed
Your workspace C
#include <stdio.h>
#include <assert.h>

int main(void) {
    int values[3] = {0};
    int count = 0;
    // Write your solution here.
    return 0;
}
Hint 1: the idea

Every reason to refuse goes into one guard at the top, with the pointer checks first. After the guard, the store and the increment can no longer fail.

Hint 2: a first step

Write the guard as values == NULL || count == NULL || *count < 0 || *count >= capacity, then add the two range checks for value. To test a negative count, use a separate variable set to -1.

Show one solution
C
#include <stdio.h>
#include <assert.h>

int append_valid(int values[], int *count, int capacity, int value) {
    if (values == NULL || count == NULL || *count < 0 || *count >= capacity ||
        value < 1 || value > 180) {
        return 0;
    }
    values[*count] = value;
    (*count)++;
    return 1;
}

int main(void) {
    int values[3] = {0};
    int count = 0;
    int ok = append_valid(values, &count, 3, 0);
    assert(!ok && count == 0);
    ok = append_valid(values, &count, 3, 25);
    assert(ok && count == 1);
    ok = append_valid(values, &count, 3, 10);
    assert(ok && count == 2);
    ok = append_valid(values, &count, 3, 40);
    assert(ok && count == 3);
    ok = append_valid(values, &count, 3, 30);
    assert(!ok && count == 3);
    int broken = -1;
    ok = append_valid(values, &broken, 3, 30);
    assert(!ok && broken == -1);
    ok = append_valid(values, NULL, 3, 30);
    assert(!ok);
    printf("Stored %d %d %d, count %d\n", values[0], values[1], values[2], count);
    printf("Capacity checks passed\n");
    return 0;
}
Text
Stored 25 10 40, count 3
Capacity checks passed

Each call that stores something runs in its own statement, and assert only checks the saved result, as Day 3 recommended: if a build defined NDEBUG, the asserts would vanish but the three values would still be stored. The refused fourth value left all three stored values and the count alone, because nothing is written until every check has passed. Passing the capacity as a parameter keeps the function honest for any array size, as long as the caller passes the real one. In the checkpoint you will see the project split these helpers into their own source file.

Was this article helpful?

Your response is saved on this device.