Skip to content

On Your Own: A Reading Log

The Course
•
120 min study

Now build a small program of your own from a brief, starting from blank files. A reading log records what you read and how many pages: each line is a lowercase title token and a page count, such as novel 20. The program prints total pages per title in alphabetical order, then the summary counts. It looks like the analyzer, and that is the point: reuse the patterns, the contracts and the tests, not unexamined code. The limits are different, and copying the analyzer's numbers without reading them is exactly the mistake this exercise is designed to catch.

Budget about two hours, outside Day 7's time estimate: this is a whole small library with its tests and an application, not one function. If your time is short, finish the library and its tests first; they are the part that proves the contracts.

The brief. Accept titles of 1 to 23 lowercase letters and page counts of 1 to 500. Store at most 100 records in a growing collection that takes an injected allocator. Print title: N sessions, P pages for each title in alphabetical order, without reordering the stored records, then Accepted, Total and Rejected lines. Reject malformed and overlong lines once each and keep reading. Allocation failure is fatal and must still release everything.

Acceptance cases. novel 20, essay 10, novel 30 and broken 0 give essay: 1 sessions, 10 pages, novel: 2 sessions, 50 pages, Accepted: 3, Total: 60 pages, Rejected: 1. Empty input gives No records and three zeros. novel 500 is accepted and novel 501 rejected. The 101st valid record is rejected.

Required tests. At least: parser rejections that leave a sentinel record unchanged (including novel 501 and an uppercase title), novel 500 accepted, one forced allocation failure with the probe (a failed growth that keeps the old records, or a failed report that prints nothing), the 101st record rejected, and live == 0 after destroy.

Predict and run

Read the program before pressing Run and write down its output.

Predict before running C
#include <stdio.h>

typedef struct { int pages; } Entry;

static int set_pages(Entry *out, int pages) {
    if (pages < 1 || pages > 500) { return 0; }
    out->pages = pages;
    return 1;
}

int main(void) {
    Entry sentinel = {77};
    int first = set_pages(&sentinel, 500);
    printf("%d %d\n", first, sentinel.pages);
    int second = set_pages(&sentinel, 501);
    printf("%d %d\n", second, sentinel.pages);
    return 0;
}
Check your prediction
Text
1 500
0 500

500 is the top of the range, so the first call succeeds and stores it. 501 fails, and the record keeps the value it had: that is the commit-on-success contract, and it is what your sentinel tests check. Work out each expected result like this, by hand, before any code exists, so your tests have something independent to compare with.

What you already have

  • A record parser that commits only on success (Day 4), with the page range instead of minutes.
  • A growing collection with validate, grow through a temporary, store, count (Day 3).
  • An injected allocator and a probe that fails a chosen call and counts live blocks (Day 6). The probe is already in the test file.
  • A sorted copy and a grouping pass (Day 5), so stored order never changes.
  • A line loop that drains overlong lines (Day 4) and one cleanup path in main (Day 6).

Build it

Exercise

Your turn: the reading log

One workspace holds everything: reading_log.h and reading_log.c for the library, test_reading_log.c for your tests, and main.c for the application, with the acceptance input already in the stdin box. While RUN_TESTS at the top of main.c is 1, Run calls your tests; set it to 0 to run the application on the stdin box. The library exists once, so a fix made for a failing test is already in the application. Your edits are saved in this browser, but a cleared browser or another device starts blank, so copy your files somewhere safe at the end of each sitting. With RUN_TESTS set to 0, the finished application prints, for the prefilled input:

Shell
essay: 1 sessions, 10 pages
novel: 2 sessions, 50 pages
Accepted: 3
Total: 60 pages
Rejected: 1
Your workspace: library, tests and application C
#include "reading_log.h" #include <stdio.h> /* 1 while you build the library: main runs your tests in test_reading_log.c. Set it to 0 to run the application on the stdin box. */ #define RUN_TESTS 1 int run_tests(void); /* defined in test_reading_log.c */ int main(void) { if (RUN_TESTS) { return run_tests(); } /* Read lines from stdin, store valid records, print the report and the Accepted, Total and Rejected lines, and release everything on every exit. */ printf("Not written yet\n"); return 0; } #ifndef READING_LOG_H #define READING_LOG_H #include <stddef.h> #include <stdio.h> /* Write your limits, record type, status enum, allocator type and the collection type here, with a contract comment above every function. */ #endif #include "reading_log.h" #include <stdlib.h> #include <string.h> /* Write the parser, the collection and the report here. */ #include "reading_log.h" #include <assert.h> #include <stdio.h> #include <stdlib.h> /* A probe allocator, as on Day 6: fails call number fail_at and counts live blocks. Pass probe_resize, probe_release and &probe to your collection's allocator. */ typedef struct { size_t calls; size_t fail_at; size_t live; } Probe; static void *probe_resize(void *context, void *old, size_t bytes) { Probe *probe = context; ++probe->calls; if (probe->calls == probe->fail_at) { return NULL; } int new_block = old == NULL; void *result = realloc(old, bytes); if (result != NULL && new_block) { ++probe->live; } return result; } static void probe_release(void *context, void *storage) { Probe *probe = context; if (storage != NULL) { --probe->live; free(storage); } } int run_tests(void); /* main.c calls this while RUN_TESTS is 1 */ int run_tests(void) { Probe probe = {0, 0, 0}; (void)probe_resize; (void)probe_release; /* Write your tests here, then print a success line at the end. */ printf("No checks yet: %zu calls\n", probe.calls); return 0; } novel 20 essay 10 novel 30 broken 0
Hint 1: the idea

Write the header first, with a contract comment for every function: what it requires, what it changes on success, and what it leaves alone on failure. Each required test then checks one of those sentences. Decide the limits (23, 500, 100) once, as named constants, so no number from the analyzer survives by accident.

Hint 2: a first step

Start with the parser alone: declare it and a Reading record type in the header, give it a body that always fails, and write the sentinel tests for novel 501, Novel 20 and "" plus the novel 500 success test. Run with RUN_TESTS at 1: the success test fails, which tells you the harness is really checking something. Then make the parser pass before you write any collection code.

Check your work

There is no single reference program for this brief; many designs are correct. Instead, check yours against this list. Each item is a claim your own tests or runs must show, not something to take on trust.

  • Acceptance input: with RUN_TESTS at 0, the application prints exactly the five lines above. With the stdin box emptied, it prints No records, Accepted: 0, Total: 0 pages, Rejected: 0.
  • Limits: novel 500 accepted, novel 501 and novel 0 rejected; a 23-letter title accepted and a 24-letter one rejected; the 101st valid record reported as full, not stored.
  • Failure contracts: every rejected parse leaves the sentinel unchanged; your forced allocation failure leaves the collection's pointer, length and capacity as they were (or prints nothing, for a failed report); probe.live is 0 after destroy.
  • Stored order: after a report, the first stored record is still the first one appended.
  • Each mutation must be caught: accept 0 pages, keep the analyzer's 180 as the page limit, skip the release in destroy, and assign realloc's result straight to data. Each must make one of your tests fail; the last one only does if your growth-failure test checks that the old records are still reachable. If a mutation survives, add the test that would have caught it.
  • Calls that change state run in their own statement, with assert checking the saved status.

If an item fails, the matching lesson is the place to look: Day 4 for parsing and line recovery, Day 3 for growth, Day 5 for the report, Day 6 for the allocator and cleanup.

Mistakes worth checking for

  • novel 300 is rejected. The page limit is still the analyzer's 180: the copied number was never re-read against the brief.
  • Titles are merged in the report. The report groups an unsorted array, or sorts by pages instead of by title.
  • The stored order changes after the report. The records were sorted in place instead of in a copy.
  • A failed growth loses earlier records. realloc was assigned straight to the owner.
  • The last title is missing from the report. The group printing happens only when the title changes, so the final group is never printed.
  • Tests depend on message wording. Assert statuses and state, and keep printed text for the application.

Was this article helpful?

Your response is saved on this device.