A valid topic and a valid number do not make a valid record on their own. reading25 has both but no separator. reading 25 extra has both and then a third field. reading 25x has a number with junk attached. Each piece of today's work checks one part of a line; this checkpoint joins them so that a record is accepted only when the whole line matches the format, and so that a rejected line leaves the caller's record exactly as it was.
The project's format: optional leading whitespace, a topic of 1 to 23 lowercase ASCII letters, at least one whitespace character, a decimal duration in 1..180 that starts with a digit (leading zeros allowed), optional trailing whitespace, and nothing else. Whitespace means space, tab, '\r' or '\n'.
Predict and run
Read the program before pressing Run. Write down its output and explain which character line[letters + 1] is.
The loop stops at the space after seven letters, so line[7] is the space and line[8] is 2. Now picture the input reading25: the loop stops at the 2, and line[letters + 1] is 5. Reaching a digit proves nothing about the separator; the parser must look at line[letters] itself and require whitespace there.
What you will use
A cursor that walks the line from left to right, so each check starts where the previous one stopped.
The bounded topic read from the tokens lesson, refusing a 24th letter instead of truncating.
The checked conversion from the strtol lesson: leading digit, cleared errno, ERANGE, end pointer and domain range.
A local candidate Record, copied to *out in one assignment only after every check has passed.
Plan before you type
Return failure if line or out is NULL. Skip leading whitespace.
Copy letters into candidate.topic, failing if a 24th letter appears. Require at least one letter.
Require at least one whitespace character, then skip all of them.
Require a digit, convert with strtol, and check ERANGE and 1..180.
Skip trailing whitespace from the end pointer and require the terminator.
Terminate the topic and assign *out = candidate.
Prove it can fail
Once the expected lines appear, break one rule at a time. Remove !is_space(*line) from the check after the topic loop: the third line, reading25, now prints ok reading 25, because nothing requires a gap between the fields. Then write the topic letters straight into out->topic instead of the candidate: every rejected line that starts with a topic now prints a changed topic instead of keep. Restore both.
Mistakes worth checking for
reading 25 extra is accepted. The parser stops after the number. Skip trailing whitespace and then require '\0'.
A 24-letter topic is stored as 23 letters. The topic loop truncates instead of failing. Two long topics would merge in the report.
reading 25 works but reading\t25\r\n does not. The separator test only accepts a space. Use one whitespace helper everywhere.
The sentinel's minutes change on a rejected line. The number is stored into out->minutes before the trailing check. Fill the candidate, then copy once.
reading +25 or reading -1 is accepted.strtol allows signs; the leading-digit check is missing.
The topic prints with junk after it. The candidate's topic was not terminated. Zero-initialize the candidate or write '\0' after the last letter.
Practice
Exercise
Your turn
Write int parse_record(const char *line, Record *out) following the plan; return 1 on success and 0 on failure. Each failure must leave the sentinel {"keep", 77} unchanged. The starter must print ok reading 25, ok coding 40, then rejected keep 77 for each of the next seven lines, and finally ok abcdefghijklmnopqrstuvw 180.
Think of the line as a sequence of regions: whitespace, letters, whitespace, digits, whitespace, end. Each region has a rule, and the cursor moves through them in order. Any surprise returns 0 before out is touched.
Hint 2: a first step
Build the parser region by region, with a local candidate record. First accept only leading whitespace and the letters, and reject everything else: the two ok lines will still be wrong, but the 24-letter topic line must already be rejected. Then add the next region and run again.
Show one solution
Run the solutionC
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
typedef struct { char topic[24]; int minutes; } Record;
static int is_space(char ch) {
return ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n';
}
int parse_record(const char *line, Record *out) {
if (line == NULL || out == NULL) { return 0; }
while (is_space(*line)) { ++line; }
Record candidate = {"", 0};
size_t length = 0;
while (*line >= 'a' && *line <= 'z') {
if (length >= sizeof candidate.topic - 1) { return 0; }
candidate.topic[length++] = *line++;
}
if (length == 0 || !is_space(*line)) { return 0; }
while (is_space(*line)) { ++line; }
if (*line < '0' || *line > '9') { return 0; }
errno = 0;
char *end = NULL;
long minutes = strtol(line, &end, 10);
if (errno == ERANGE || end == line || minutes < 1 || minutes > 180) { return 0; }
while (is_space(*end)) { ++end; }
if (*end != '\0') { return 0; }
candidate.topic[length] = '\0';
candidate.minutes = (int)minutes;
*out = candidate;
return 1;
}
int main(void) {
const char *lines[10] = {
"reading 25", " coding\t40\r\n", "reading25", "reading 25 extra", "reading",
"reading 0", "Reading 25", "abcdefghijklmnopqrstuvwx 25", "",
"abcdefghijklmnopqrstuvw 180",
};
for (size_t i = 0; i < 10; ++i) {
Record record = {"keep", 77};
if (parse_record(lines[i], &record)) {
printf("ok %s %d\n", record.topic, record.minutes);
} else {
printf("rejected %s %d\n", record.topic, record.minutes);
}
}
return 0;
}
Every rejection returns before the single *out = candidate;, which is why the sentinel survives all seven. The two long topics sit on either side of the limit: 24 letters fail, 23 letters with the maximum duration pass. sizeof candidate.topic - 1 ties the limit to the array, so changing the array size cannot leave a stale 23 behind. Tomorrow you search, sort and group the records this parser produces.
Inspect the real parser and its tests
The project's record_parse in analyzer.c follows the same plan and returns ANALYZER_INVALID or ANALYZER_OK. Its tests in test_analyzer.c loop over a list of bad lines and check after each one that the sentinel {"keep", 77} is unchanged. Run them.
Parser, collection and failure testsC#include "analyzer.h"
#include <assert.h>
#include <stdlib.h>
#include <string.h>
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;
assert(storage != NULL && probe->live > 0);
--probe->live;
free(storage);
}
int main(void) {
/* Calls that change state run in their own statement and assert checks the
saved status, so building with NDEBUG removes only the checks, not the work. */
AnalyzerStatus status;
Record out = {"keep", 77};
const char *bad[] = {"", "reading", "reading 0", "reading 181", "Read 25",
"reading -1", "reading +25", "reading 25x", "reading 25 extra",
"reading 99999999999999999999999999999", "abcdefghijklmnopqrstuvwx 25"};
for (size_t i = 0; i < sizeof bad / sizeof bad[0]; ++i) {
status = record_parse(bad[i], &out);
assert(status == ANALYZER_INVALID);
assert(strcmp(out.topic, "keep") == 0 && out.minutes == 77);
}
status = record_parse(NULL, &out);
assert(status == ANALYZER_INVALID);
status = record_parse("reading 25", NULL);
assert(status == ANALYZER_INVALID);
status = record_parse(" reading 001\r\n", &out);
assert(status == ANALYZER_OK && out.minutes == 1);
status = record_parse("abcdefghijklmnopqrstuvw 180", &out);
assert(status == ANALYZER_OK && out.minutes == 180);
Probe probe = {0, 1, 0};
Allocator allocator = {probe_resize, probe_release, &probe};
Analyzer analyzer;
analyzer_init(&analyzer, allocator);
Record reading = {"reading", 25};
Record coding = {"coding", 40};
assert(analyzer_total(&analyzer) == 0);
status = analyzer_append(&analyzer, &reading);
assert(status == ANALYZER_NOMEM);
assert(analyzer.data == NULL && analyzer.length == 0 && analyzer.capacity == 0);
probe.fail_at = 0;
for (size_t i = 0; i < 4; ++i) {
status = analyzer_append(&analyzer, &reading);
assert(status == ANALYZER_OK);
}
Record *old = analyzer.data;
size_t capacity = analyzer.capacity;
probe.fail_at = probe.calls + 1;
status = analyzer_append(&analyzer, &coding);
assert(status == ANALYZER_NOMEM);
assert(analyzer.data == old && analyzer.length == 4 && analyzer.capacity == capacity);
assert(analyzer_total(&analyzer) == 100 && probe.live == 1);
probe.fail_at = 0;
/* Passing a borrowed element back into append is safe across growth. */
status = analyzer_append(&analyzer, &analyzer.data[0]);
assert(status == ANALYZER_OK);
assert(analyzer.length == 5 && analyzer_total(&analyzer) == 125);
Record invalid = {"bad", 0};
status = analyzer_append(&analyzer, &invalid);
assert(status == ANALYZER_INVALID && analyzer.length == 5);
status = analyzer_remove(&analyzer, analyzer.length);
assert(status == ANALYZER_INVALID);
status = analyzer_remove(&analyzer, 0);
assert(status == ANALYZER_OK && analyzer.length == 4);
assert(analyzer_total(&analyzer) == 100);
analyzer_destroy(&analyzer);
analyzer_destroy(&analyzer);
assert(probe.live == 0 && analyzer.data == NULL && analyzer.capacity == 0 && analyzer.length == 0);
analyzer_init(&analyzer, allocator);
status = analyzer_append(&analyzer, &reading);
assert(status == ANALYZER_OK);
status = analyzer_append(&analyzer, &coding);
assert(status == ANALYZER_OK);
Record short_reading = {"reading", 10};
status = analyzer_append(&analyzer, &short_reading);
assert(status == ANALYZER_OK);
probe.fail_at = probe.calls + 1;
status = analyzer_report(&analyzer, stdout);
assert(status == ANALYZER_NOMEM);
assert(analyzer_total(&analyzer) == 75 && probe.live == 1);
probe.fail_at = 0;
status = analyzer_report(&analyzer, stdout);
assert(status == ANALYZER_OK);
assert(strcmp(analyzer.data[0].topic, "reading") == 0 && analyzer.data[0].minutes == 25);
assert(probe.live == 1);
status = analyzer_remove(&analyzer, 0);
assert(status == ANALYZER_OK);
assert(strcmp(analyzer.data[0].topic, "coding") == 0 && analyzer_total(&analyzer) == 50);
status = analyzer_remove(&analyzer, 1);
assert(status == ANALYZER_OK);
status = analyzer_remove(&analyzer, 0);
assert(status == ANALYZER_OK && analyzer_total(&analyzer) == 0);
for (size_t i = 0; i < ANALYZER_LIMIT; ++i) {
status = analyzer_append(&analyzer, &coding);
assert(status == ANALYZER_OK);
}
status = analyzer_append(&analyzer, &reading);
assert(status == ANALYZER_FULL);
assert(analyzer.length == ANALYZER_LIMIT && analyzer_total(&analyzer) == 40960);
analyzer_destroy(&analyzer);
assert(probe.live == 0);
(void)status; /* these are only read by assert, which NDEBUG removes */
(void)old;
(void)capacity;
puts("Analyzer checks passed");
return 0;
}
#include "analyzer.h"
#include <errno.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
static void *default_resize(void *context, void *old, size_t bytes) {
(void)context;
return realloc(old, bytes);
}
static void default_release(void *context, void *storage) {
(void)context;
free(storage);
}
Allocator analyzer_default_allocator(void) {
Allocator allocator = {default_resize, default_release, NULL};
return allocator;
}
void analyzer_init(Analyzer *analyzer, Allocator allocator) {
analyzer->data = NULL;
analyzer->length = 0;
analyzer->capacity = 0;
analyzer->allocator = allocator;
}
void analyzer_destroy(Analyzer *analyzer) {
if (analyzer->data != NULL) {
analyzer->allocator.release(analyzer->allocator.context, analyzer->data);
}
analyzer->data = NULL;
analyzer->length = 0;
analyzer->capacity = 0;
}
static int whitespace(char ch) {
return ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n';
}
static int valid_record(const Record *record) {
if (record == NULL || record->minutes < 1 || record->minutes > 180) {
return 0;
}
size_t i = 0;
while (i < TOPIC_CAPACITY && record->topic[i] >= 'a' && record->topic[i] <= 'z') {
++i;
}
return i > 0 && i < TOPIC_CAPACITY && record->topic[i] == '\0';
}
AnalyzerStatus record_parse(const char *line, Record *out) {
if (line == NULL || out == NULL) {
return ANALYZER_INVALID;
}
while (whitespace(*line)) { ++line; }
Record candidate = {{0}, 0};
size_t length = 0;
while (*line >= 'a' && *line <= 'z') {
if (length >= TOPIC_CAPACITY - 1) { return ANALYZER_INVALID; }
candidate.topic[length++] = *line++;
}
if (length == 0 || !whitespace(*line)) { return ANALYZER_INVALID; }
while (whitespace(*line)) { ++line; }
/* Require a decimal digit first: signed notation is outside this format. */
if (*line < '0' || *line > '9') { return ANALYZER_INVALID; }
errno = 0;
char *end = NULL;
long minutes = strtol(line, &end, 10);
if (errno == ERANGE || end == line || minutes < 1 || minutes > 180) {
return ANALYZER_INVALID;
}
while (whitespace(*end)) { ++end; }
if (*end != '\0') { return ANALYZER_INVALID; }
candidate.minutes = (int)minutes;
*out = candidate;
return ANALYZER_OK;
}
AnalyzerStatus analyzer_append(Analyzer *analyzer, const Record *record) {
if (!valid_record(record)) { return ANALYZER_INVALID; }
if (analyzer->length >= ANALYZER_LIMIT) { return ANALYZER_FULL; }
/* A caller may pass &data[i]. Copy it before realloc can invalidate it. */
Record candidate = *record;
if (analyzer->length == analyzer->capacity) {
size_t capacity = analyzer->capacity == 0 ? 4 : analyzer->capacity * 2;
if (capacity > ANALYZER_LIMIT) { capacity = ANALYZER_LIMIT; }
if (capacity > SIZE_MAX / sizeof *analyzer->data) { return ANALYZER_NOMEM; }
void *grown = analyzer->allocator.resize(analyzer->allocator.context,
analyzer->data, capacity * sizeof *analyzer->data);
if (grown == NULL) { return ANALYZER_NOMEM; }
analyzer->data = grown;
analyzer->capacity = capacity;
}
analyzer->data[analyzer->length] = candidate;
++analyzer->length;
return ANALYZER_OK;
}
AnalyzerStatus analyzer_remove(Analyzer *analyzer, size_t index) {
if (index >= analyzer->length) { return ANALYZER_INVALID; }
size_t following = analyzer->length - index - 1;
if (following > 0) {
memmove(&analyzer->data[index], &analyzer->data[index + 1],
following * sizeof *analyzer->data);
}
--analyzer->length;
return ANALYZER_OK;
}
long analyzer_total(const Analyzer *analyzer) {
long total = 0;
for (size_t i = 0; i < analyzer->length; ++i) { total += analyzer->data[i].minutes; }
return total;
}
static int compare_records(const void *left, const void *right) {
const Record *a = left;
const Record *b = right;
int topic = strcmp(a->topic, b->topic);
if (topic != 0) { return topic; }
return (a->minutes > b->minutes) - (a->minutes < b->minutes);
}
AnalyzerStatus analyzer_report(const Analyzer *analyzer, FILE *output) {
if (analyzer->length == 0) {
fprintf(output, "No records\n");
return ANALYZER_OK;
}
Record *sorted = analyzer->allocator.resize(analyzer->allocator.context, NULL,
analyzer->length * sizeof *sorted);
if (sorted == NULL) { return ANALYZER_NOMEM; }
memcpy(sorted, analyzer->data, analyzer->length * sizeof *sorted);
qsort(sorted, analyzer->length, sizeof *sorted, compare_records);
size_t i = 0;
while (i < analyzer->length) {
size_t start = i;
long minutes = 0;
while (i < analyzer->length && strcmp(sorted[start].topic, sorted[i].topic) == 0) {
minutes += sorted[i].minutes;
++i;
}
fprintf(output, "%s: %zu sessions, %ld minutes\n", sorted[start].topic, i - start, minutes);
}
analyzer->allocator.release(analyzer->allocator.context, sorted);
return ANALYZER_OK;
}
#ifndef ANALYZER_H
#define ANALYZER_H
#include <stddef.h>
#include <stdio.h>
#define TOPIC_CAPACITY 24
#define ANALYZER_LIMIT 1024
typedef enum { ANALYZER_OK, ANALYZER_INVALID, ANALYZER_FULL, ANALYZER_NOMEM } AnalyzerStatus;
typedef struct { char topic[TOPIC_CAPACITY]; int minutes; } Record;
/* resize has realloc semantics: failure preserves old storage. release frees it.
Both callbacks use the same allocator/context, which must outlive the analyzer. */
typedef void *(*ResizeFn)(void *context, void *old, size_t bytes);
typedef void (*ReleaseFn)(void *context, void *storage);
typedef struct { ResizeFn resize; ReleaseFn release; void *context; } Allocator;
/* Owns data. Do not shallow-copy this struct or free data yourself.
Invariant: length <= capacity <= ANALYZER_LIMIT; only [0,length) is initialized.
Borrowed element pointers expire after successful growth, removal or destroy. */
typedef struct {
Record *data;
size_t length;
size_t capacity;
Allocator allocator;
} Analyzer;
Allocator analyzer_default_allocator(void);
/* Initialize once, using a valid allocator. Destroy before reinitializing. */
void analyzer_init(Analyzer *analyzer, Allocator allocator);
void analyzer_destroy(Analyzer *analyzer);
/* Lowercase ASCII topic (1..23 letters), whitespace, decimal duration 1..180.
Leading/trailing whitespace is allowed. No extra fields. Failure preserves out. */
AnalyzerStatus record_parse(const char *line, Record *out);
/* Failure leaves contents, length and capacity unchanged. Copies record by value. */
AnalyzerStatus analyzer_append(Analyzer *analyzer, const Record *record);
AnalyzerStatus analyzer_remove(Analyzer *analyzer, size_t index);
/* Empty total is zero. Caller supplies an initialized analyzer. */
long analyzer_total(const Analyzer *analyzer);
/* Sort a temporary copy by topic/minutes. Does not reorder stored records.
Allocation failure prints nothing. Caller checks ferror(output) for I/O errors. */
AnalyzerStatus analyzer_report(const Analyzer *analyzer, FILE *output);
#endif
Check your prediction
Read record_parse and find where it checks the topic size, where it detects numeric overflow, and the one line that commits the candidate. The allocation callbacks used by the rest of these tests are introduced on Days 5 and 6.
Completion is saved in this browser only. It does not measure mastery.