Skip to content

Checkpoint: A Growing Collection

The Course
•
50 min study

Today you separated length from capacity, resized with realloc without losing the original block, and removed elements without leaving gaps. list_push in Grow Without Losing the Original only ever added at the end. This checkpoint asks for the harder operation that combines all three lessons: insert a value at any position. It must validate the position, grow only when full, never allocate past a maximum, shift the later elements up without losing any, and leave everything unchanged when any step fails. The project's analyzer_append is the at-the-end special case of this.

Predict and run

Read the program before pressing Run. Write down its output and say which capacity the fifth append needs.

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

int main(void) {
    size_t capacity = 0;
    for (int growth = 0; growth < 3; ++growth) {
        capacity = capacity == 0 ? 4 : capacity * 2;
        printf("%zu\n", capacity);
    }
    return 0;
}
Check your prediction
Text
4
8
16

The first growth jumps from 0 to 4; later ones double. A fifth element finds 4 elements in 4 slots and needs a larger block. Doubling only lands exactly on a limit by luck: with a maximum of 6 elements, doubling 4 would ask for 8 slots, two of which could never be used. A collection with a maximum should cap the new capacity at that maximum.

What you will use

  • The three-field struct List with data, length and capacity, starting as {NULL, 0, 0}.
  • Named outcomes: STATUS_INVALID, STATUS_FULL and STATUS_NOMEM, with input checked first.
  • A temporary for realloc, committed together with the new capacity only on success.
  • memmove from Remove Without Leaving a Gap, this time shifting elements toward the end.

Plan before you type

Goals, not statements.

  1. Write the contract: which positions are valid, which failure wins, and what a failure leaves behind.
  2. Make sure there is a free slot before anything moves, without ever holding more than LIST_LIMIT slots.
  3. Open a gap at index without losing or duplicating an element, including when index is 0 and when it equals the length.
  4. Compare every line of your output with the expected output, then run the "Prove it can fail" steps below.

Practice

Exercise

Your turn

Write Status list_insert(List *list, size_t index, int value) for a list of at most LIST_LIMIT (6) elements:

  • index may be anything from 0 to the current length; index == length appends. Any other index, or a value below 1, is STATUS_INVALID, reported before a full list.
  • A list that already holds 6 elements is STATUS_FULL.
  • When the list has no free slot, grow it: 4 slots for an empty list, otherwise double, but never more than LIST_LIMIT slots. A failed resize is STATUS_NOMEM.
  • On success, the elements from index onward move up one place and value takes position index. On every failure, data, length and capacity are unchanged.

The starter's main must print:

Shell
20 at 0: ok, capacity 4: 20
40 at 1: ok, capacity 4: 20 40
10 at 0: ok, capacity 4: 10 20 40
30 at 2: ok, capacity 4: 10 20 30 40
5 at 9: invalid, capacity 4: 10 20 30 40
50 at 4: ok, capacity 6: 10 20 30 40 50
1 at 0: ok, capacity 6: 1 10 20 30 40 50
60 at 6: full, capacity 6: 1 10 20 30 40 50
destroyed: length 0, capacity 0
Your workspace C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define LIST_LIMIT 6
typedef enum { STATUS_OK, STATUS_INVALID, STATUS_FULL, STATUS_NOMEM } Status;
typedef struct { int *data; size_t length; size_t capacity; } List;

const char *status_name(Status status) {
    switch (status) {
    case STATUS_OK: return "ok";
    case STATUS_INVALID: return "invalid";
    case STATUS_FULL: return "full";
    case STATUS_NOMEM: return "out of memory";
    }
    return "unknown";
}

void list_destroy(List *list) {
    free(list->data);
    list->data = NULL;
    list->length = 0;
    list->capacity = 0;
}

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

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

int main(void) {
    List list = {NULL, 0, 0};
    show("20 at 0", list_insert(&list, 0, 20), &list);
    show("40 at 1", list_insert(&list, 1, 40), &list);
    show("10 at 0", list_insert(&list, 0, 10), &list);
    show("30 at 2", list_insert(&list, 2, 30), &list);
    show("5 at 9", list_insert(&list, 9, 5), &list);
    show("50 at 4", list_insert(&list, 4, 50), &list);
    show("1 at 0", list_insert(&list, 0, 1), &list);
    show("60 at 6", list_insert(&list, 6, 60), &list);
    list_destroy(&list);
    printf("destroyed: length %zu, capacity %zu\n", list.length, list.capacity);
    return 0;
}
Hint 1: the idea

Get a free slot first, then make the gap, then fill it. The growth step is the only one that can fail after validation, so it comes before anything moves. The gap is made by moving the elements from index to the end, which is length - index elements.

Hint 2: a first step

Write the validation and the growth, then store the value at list->length as if every insert were an append. Run it: the first two lines are already right, and the third shows 20 40 10 instead of 10 20 40. What is left is making room at index before the store.

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

#define LIST_LIMIT 6
typedef enum { STATUS_OK, STATUS_INVALID, STATUS_FULL, STATUS_NOMEM } Status;
typedef struct { int *data; size_t length; size_t capacity; } List;

const char *status_name(Status status) {
    switch (status) {
    case STATUS_OK: return "ok";
    case STATUS_INVALID: return "invalid";
    case STATUS_FULL: return "full";
    case STATUS_NOMEM: return "out of memory";
    }
    return "unknown";
}

void list_destroy(List *list) {
    free(list->data);
    list->data = NULL;
    list->length = 0;
    list->capacity = 0;
}

/* Inserts value before position index (index == length appends).
   Invalid input (value < 1, index > length) is reported before a full list.
   Never holds more than LIST_LIMIT slots.
   Failure leaves data, length and capacity unchanged. */
Status list_insert(List *list, size_t index, int value) {
    if (value < 1 || index > list->length) { return STATUS_INVALID; }
    if (list->length >= LIST_LIMIT) { return STATUS_FULL; }
    if (list->length == list->capacity) {
        size_t capacity = list->capacity == 0 ? 4 : list->capacity * 2;
        if (capacity > LIST_LIMIT) { capacity = LIST_LIMIT; }
        int *grown = realloc(list->data, capacity * sizeof *grown);
        if (grown == NULL) { return STATUS_NOMEM; }
        list->data = grown;
        list->capacity = capacity;
    }
    memmove(&list->data[index + 1], &list->data[index],
            (list->length - index) * sizeof *list->data);
    list->data[index] = value;
    ++list->length;
    return STATUS_OK;
}

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

int main(void) {
    List list = {NULL, 0, 0};
    show("20 at 0", list_insert(&list, 0, 20), &list);
    show("40 at 1", list_insert(&list, 1, 40), &list);
    show("10 at 0", list_insert(&list, 0, 10), &list);
    show("30 at 2", list_insert(&list, 2, 30), &list);
    show("5 at 9", list_insert(&list, 9, 5), &list);
    show("50 at 4", list_insert(&list, 4, 50), &list);
    show("1 at 0", list_insert(&list, 0, 1), &list);
    show("60 at 6", list_insert(&list, 6, 60), &list);
    list_destroy(&list);
    printf("destroyed: length %zu, capacity %zu\n", list.length, list.capacity);
    return 0;
}
Text
20 at 0: ok, capacity 4: 20
40 at 1: ok, capacity 4: 20 40
10 at 0: ok, capacity 4: 10 20 40
30 at 2: ok, capacity 4: 10 20 30 40
5 at 9: invalid, capacity 4: 10 20 30 40
50 at 4: ok, capacity 6: 10 20 30 40 50
1 at 0: ok, capacity 6: 1 10 20 30 40 50
60 at 6: full, capacity 6: 1 10 20 30 40 50
destroyed: length 0, capacity 0

Validation comes first, so 5 at 9 changes nothing. The growth step runs only when the list is full, keeps the new block in grown until realloc has succeeded, and caps the capacity, which is why the fifth element brings the capacity to 6 rather than 8. Only then does memmove shift length - index elements up by one; it is memmove, not memcpy, because the source and destination overlap. For an append, index == length moves zero elements. The limit is checked before growth, so the collection never allocates for an element it would refuse. The stated output assumes allocation succeeds; Day 6 makes that assumption testable. Tomorrow you turn text lines into validated values to insert.

Prove it can fail

When your output matches, make one change at a time and run again. Delete the line that caps the capacity: the 50 at 4 line now reports capacity 8. Nothing is written out of bounds, because the FULL check still stops the list at 6, but two slots are allocated that can never be used. Restore it. Then change the shift count to list->length - index - 1. On the very first insert, the length and the index are both 0, so the unsigned count wraps to a huge number and memmove reads and writes far past the block. That is undefined behavior: the browser run may crash or print nonsense, and a local build with -fsanitize=address stops at once with negative-size-param. Restore it. Finally, replace the temporary with list->data = realloc(list->data, ...): the output does not change at all, which shows that success-only tests cannot catch the leak this causes on failure. Day 6 adds the controlled allocator that does.

One subtle case: inserting from yourself

A function that takes a pointer to the value, such as insert(list, 0, &list->data[2]), must copy the value before resizing or shifting, because a successful realloc can move the block, and the shift changes what is stored at that address. Here the value arrives as an int parameter, which is already a copy, so the problem cannot happen. The project's record API takes const Record *, so it makes the copy explicitly before growing.

Mistakes worth checking for

  • Capacity stays at 0 forever. The growth formula is capacity * 2 with no special case for 0. Start at 4.
  • A failed insert still changes length or capacity. A field was updated before the step that can fail. Update capacity only next to data, after the NULL check.
  • An element is duplicated and the last one is lost. The shift moved one element too few, or used a loop that copies upward from the front and overwrites the values it has yet to move.
  • Inserting at the end is rejected. The index check is index >= length. Appending is index == length, which is valid.
  • Invalid input is reported as full. With 6 elements, inserting 0 must still say invalid, because input is checked first.

Was this article helpful?

Your response is saved on this device.