Skip to content

Checkpoint: A Bounded Record API

The Course
•
50 min study

Before you own heap memory, prove you can keep a collection correct when the caller supplies the storage. The caller passes an array, its capacity (how many elements fit) and a pointer to its length (how many are active). Name Failure Outcomes appended one value at a time. This checkpoint appends a whole batch, and the caller wants all of it or none of it: half a batch in the log is worse than a clear refusal. That needs every idea from today, in a combination you have not written yet: a contract, a named outcome for each failure, size arithmetic that cannot wrap, and a guarantee that a rejected call changes nothing.

Why a pointer to the length? The function must update it on success, and C passes arguments by value. Passing &length lets the function change the caller's variable, and it makes the change visible at the call site: whoever writes &length knows it may move.

Predict and run

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

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

int main(void) {
    size_t length = 0;
    int data[2] = {0};
    if (length < 2) { data[length++] = 25; }
    printf("%zu %d\n", length, data[0]);
    return 0;
}
Check your prediction
Text
1 25

data[length++] = 25 stores at index 0, the old length, and then increases the length to 1. The next free slot always has the index equal to the current length. The bound length < 2 comes before the write: once an out-of-range write has happened, it is too late to check. Writing past the end of an array is undefined behavior, and it often corrupts whatever variable happens to sit next to the array, with no crash to tell you.

What you will use

  • A contract comment that states preconditions, the success change, the failure guarantee and which failure wins.
  • The status enum from Name Failure Outcomes: STATUS_OK, STATUS_INVALID and STATUS_FULL.
  • Unsigned size arithmetic from Sizes and Arithmetic Boundaries: a room check that cannot wrap.
  • Validate, then commit, now for many values at once.

Plan before you type

Goals, not statements; the statements are your design.

  1. Write the contract comment first, including what happens to a batch with one bad value and to a batch that does not fit.
  2. Decide how the function can know the whole batch is acceptable before it writes anything.
  3. Decide how to compare "how much room is left" with the batch size using only size_t values that cannot wrap.
  4. Check your output against every line below, especially the two refused batches and the empty one.

Practice

Exercise

Your turn

Write Status append_all(int data[], size_t *length, size_t capacity, const int values[], size_t count). It appends all count values, or none of them:

  • STATUS_INVALID if any value is outside 1..180 (reported before a lack of room).
  • STATUS_FULL if the whole batch does not fit in the remaining space.
  • Otherwise every value is appended in order and the result is STATUS_OK. An empty batch (count 0) always succeeds and changes nothing.

On any failure, data and *length are unchanged. With the starter's capacity of 4, the program must print:

Shell
{25, 30}: ok, length 2: 25 30
{40, 0}: invalid input, length 2: 25 30
{40, 50, 60}: storage full, length 2: 25 30
{40, 50}: ok, length 4: 25 30 40 50
{}: ok, length 4: 25 30 40 50
Your workspace C
#include <stdio.h>
#include <stddef.h>

typedef enum { STATUS_OK, STATUS_INVALID, STATUS_FULL } Status;

const char *status_name(Status status) {
    switch (status) {
    case STATUS_OK: return "ok";
    case STATUS_INVALID: return "invalid input";
    case STATUS_FULL: return "storage full";
    }
    return "unknown status";
}

/* Write append_all here, with its contract comment. */

void show(const char *label, Status status, const int data[], size_t length) {
    printf("%s: %s, length %zu:", label, status_name(status), length);
    for (size_t i = 0; i < length; ++i) { printf(" %d", data[i]); }
    printf("\n");
}

int main(void) {
    int data[4] = {0};
    size_t length = 0;
    int first[2] = {25, 30};
    int bad[2] = {40, 0};
    int big[3] = {40, 50, 60};
    int last[2] = {40, 50};
    show("{25, 30}", append_all(data, &length, 4, first, 2), data, length);
    show("{40, 0}", append_all(data, &length, 4, bad, 2), data, length);
    show("{40, 50, 60}", append_all(data, &length, 4, big, 3), data, length);
    show("{40, 50}", append_all(data, &length, 4, last, 2), data, length);
    show("{}", append_all(data, &length, 4, NULL, 0), data, length);
    return 0;
}
Hint 1: the idea

A single pass that checks and writes as it goes cannot keep the "none of them" promise: by the time it meets the bad value, the good ones before it are already stored. Separate the checking from the writing.

Hint 2: a first step

Write the obvious version first: a loop that does what store_add did for each value (check it, check room, store it, return on failure). Run it and compare the second and third lines with the expected output. The length 3 and the stray 40 you see are the partial batch the brief forbids; the rest of your design is about making them impossible.

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

typedef enum { STATUS_OK, STATUS_INVALID, STATUS_FULL } Status;

const char *status_name(Status status) {
    switch (status) {
    case STATUS_OK: return "ok";
    case STATUS_INVALID: return "invalid input";
    case STATUS_FULL: return "storage full";
    }
    return "unknown status";
}

/* Requires: data and length are valid, *length <= capacity,
   values holds count ints (it may be NULL only when count is 0).
   Appends all count values or none of them.
   Any duration outside 1..180 is reported before a lack of room.
   Failure leaves data and *length unchanged. */
Status append_all(int data[], size_t *length, size_t capacity,
                  const int values[], size_t count) {
    for (size_t i = 0; i < count; ++i) {
        if (values[i] < 1 || values[i] > 180) { return STATUS_INVALID; }
    }
    if (count > capacity - *length) { return STATUS_FULL; }
    for (size_t i = 0; i < count; ++i) {
        data[*length + i] = values[i];
    }
    *length += count;
    return STATUS_OK;
}

void show(const char *label, Status status, const int data[], size_t length) {
    printf("%s: %s, length %zu:", label, status_name(status), length);
    for (size_t i = 0; i < length; ++i) { printf(" %d", data[i]); }
    printf("\n");
}

int main(void) {
    int data[4] = {0};
    size_t length = 0;
    int first[2] = {25, 30};
    int bad[2] = {40, 0};
    int big[3] = {40, 50, 60};
    int last[2] = {40, 50};
    show("{25, 30}", append_all(data, &length, 4, first, 2), data, length);
    show("{40, 0}", append_all(data, &length, 4, bad, 2), data, length);
    show("{40, 50, 60}", append_all(data, &length, 4, big, 3), data, length);
    show("{40, 50}", append_all(data, &length, 4, last, 2), data, length);
    show("{}", append_all(data, &length, 4, NULL, 0), data, length);
    return 0;
}
Text
{25, 30}: ok, length 2: 25 30
{40, 0}: invalid input, length 2: 25 30
{40, 50, 60}: storage full, length 2: 25 30
{40, 50}: ok, length 4: 25 30 40 50
{}: ok, length 4: 25 30 40 50

The first loop only reads, so returning from it cannot leave anything half-done. The room check is count > capacity - *length. The subtraction is safe because the precondition promises *length <= capacity, so the result is the free space and never wraps. The tempting *length + count > capacity can wrap for a huge count and then claim the batch fits. Only after both checks does the second loop write, and the length moves once, by the whole batch. The empty batch passes both checks and writes nothing, which is exactly "all of nothing". Tomorrow the storage moves to the heap, and your function, not the caller, becomes responsible for its size and its release.

Prove it can fail

Once your solution prints the expected lines, break it on purpose. Move the room check above the validity loop: every line still matches, because no batch here is both invalid and too big. Add a call with {0, 1, 2, 3, 4} (invalid and too big) and the output now disagrees with your contract, which said invalid input wins. Then put the store back inside the checking loop, as in Hint 2's first version: the second line shows length 3. Restore your solution afterward.

Mistakes worth checking for

  • A refused batch leaves some values behind. Something is written before every check has passed. Check the whole batch first.
  • The last free slots are refused. The room check is off by one: a batch of 2 must fit when exactly 2 slots are free.
  • *length + count > capacity. Correct for small numbers, but it can wrap for a huge count. Subtract on the side that cannot go below zero.
  • The length is wrong after a success. It was increased inside the copying loop and after it, or not at all.
  • The empty batch reports a failure. A check such as count == 0 was treated as an error; the contract says it succeeds.

Was this article helpful?

Your response is saved on this device.