A good test of whether you understand a library is to add to it without breaking it. Your extension is analyzer_topic_total: given an analyzer and a topic, return the total minutes recorded for that topic. It sounds like a one-line loop, and the loop is short. The work is in the decisions around it: where it lives, what it promises, what it must not do, and which tests prove those promises. After that, you can download the project and run it with a real compiler, including the sanitizer build that browsers cannot offer.
Predict and run
Read the program before pressing Run and write down its output.
Predict before runningC
#include <stdio.h>
#include <string.h>
int main(void) {
const char *topics[3] = {"reading", "coding", "reading"};
int minutes[3] = {25, 40, 10};
long total = 0;
for (size_t i = 0; i < 3; ++i) {
if (strcmp(topics[i], "reading") == 0) { total += minutes[i]; }
}
printf("%ld\n", total);
return 0;
}
Check your prediction
Text
35
Only the two reading entries contribute, 25 and 10. Change the search to a missing topic and the loop finds no matches and returns 0, with no special case needed.
Design the function before writing it
Answer these questions first, and write the answers into the header comment:
Signature.long analyzer_topic_total(const Analyzer *analyzer, const char *topic); The const on the analyzer promises the query cannot change storage, and the compiler enforces it. long matches analyzer_total, because one topic can hold all 1024 records.
Absent topic and empty analyzer. Both return 0. A topic with no minutes and a topic with no records are the same answer for a total.
Invalid arguments. A NULL topic returns 0 instead of crashing in strcmp. A NULL analyzer is a precondition violation, as for analyzer_total.
No allocation, no sorting. Unlike the report, this query walks the stored records in place. It cannot fail, so it needs no status, and it cannot reorder anything.
Placement. The definition goes in analyzer.c, the declaration in analyzer.h. The application may print it, but the calculation belongs to the library, where tests can call it without arranging stdin.
Tests that prove it
The tests go in their own entry file beside the library, test_topic_total.c, so they call the real analyzer_append and analyzer_remove. They need: an empty analyzer gives 0; after appending reading 25, coding 40 and reading 10, reading gives 35 and coding 40; painting gives 0; a NULL topic gives 0; and after analyzer_remove(&analyzer, 0), reading gives 10. The last case matters: it proves the function reads only the active records, not stale data in the spare slot after a removal. Every call that changes the analyzer runs in its own statement, with assert checking the saved status, as in test_analyzer.c.
Practice
Exercise
Your turn
Extend the real library in the tabs below:
analyzer.h: declare long analyzer_topic_total(const Analyzer *analyzer, const char *topic); with a one-line contract comment.
analyzer.c: define it at the end of the file, following the design above.
test_topic_total.c (the entry file): add the assertions from Tests that prove it, then print the reading total after the removal. The starter's last line prints No checks yet so that it can't report success before you write anything; change it to Topic total checks passed. When everything passes, the output is:
Shell
reading after removal: 10Topic total checks passed
Mutation: make your loop stop one record early (i + 1 < analyzer->length) and run. One of your assertions must fail. Restore the loop.
Your workspace: the analyzer libraryC#include "analyzer.h"
#include <assert.h>
#include <stdio.h>
int main(void) {
Analyzer analyzer;
analyzer_init(&analyzer, analyzer_default_allocator());
AnalyzerStatus status;
Record records[3] = {{"reading", 25}, {"coding", 40}, {"reading", 10}};
for (size_t i = 0; i < 3; ++i) {
status = analyzer_append(&analyzer, &records[i]);
assert(status == ANALYZER_OK);
}
/* Write your assertions for analyzer_topic_total here: before the appends
(move them up), after them, for an absent topic, for NULL, and after
analyzer_remove(&analyzer, 0). Then print the reading total. */
(void)status;
analyzer_destroy(&analyzer);
puts("No checks yet: add your assertions above");
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
Hint 1: the idea
Filter, then accumulate, over analyzer->data[0] to analyzer->data[length - 1], never up to capacity. The NULL check must come before the loop, because strcmp with a null pointer is undefined behavior.
Hint 2: a first step
Add the declaration and a definition that just returns 0, then write only the empty-analyzer assertion (above the appends) and the painting one, and run: both pass against the stub. Now add the reading == 35 assertion and run again; it fails, naming its line. That failing line is what the loop has to fix.
Show one solution
The new function, added to analyzer.c, with its declaration in analyzer.h:
C
/* Total minutes for topic among the stored records. Absent topic, empty analyzer or NULL topic: 0. Reads only; cannot fail. */long analyzer_topic_total(const Analyzer *analyzer, const char *topic) { if (topic == NULL) { return 0; } long total = 0; for (size_t i = 0; i < analyzer->length; ++i) { if (strcmp(analyzer->data[i].topic, topic) == 0) { total += analyzer->data[i].minutes; } } return total;}
All three files together, with the tests:
Run the extended library and its testsC#include "analyzer.h"
#include <assert.h>
#include <stdio.h>
int main(void) {
Analyzer analyzer;
analyzer_init(&analyzer, analyzer_default_allocator());
AnalyzerStatus status;
assert(analyzer_topic_total(&analyzer, "reading") == 0);
Record records[3] = {{"reading", 25}, {"coding", 40}, {"reading", 10}};
for (size_t i = 0; i < 3; ++i) {
status = analyzer_append(&analyzer, &records[i]);
assert(status == ANALYZER_OK);
}
assert(analyzer_topic_total(&analyzer, "reading") == 35);
assert(analyzer_topic_total(&analyzer, "coding") == 40);
assert(analyzer_topic_total(&analyzer, "painting") == 0);
assert(analyzer_topic_total(&analyzer, NULL) == 0);
status = analyzer_remove(&analyzer, 0);
assert(status == ANALYZER_OK);
assert(analyzer_topic_total(&analyzer, "reading") == 10);
assert(analyzer_total(&analyzer) == 50);
(void)status; /* only read by assert, which NDEBUG removes */
printf("reading after removal: %ld\n", analyzer_topic_total(&analyzer, "reading"));
analyzer_destroy(&analyzer);
puts("Topic total 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;
}
/* Total minutes for topic among the stored records.
Absent topic, empty analyzer or NULL topic: 0. Reads only; cannot fail. */
long analyzer_topic_total(const Analyzer *analyzer, const char *topic) {
if (topic == NULL) { return 0; }
long total = 0;
for (size_t i = 0; i < analyzer->length; ++i) {
if (strcmp(analyzer->data[i].topic, topic) == 0) { total += analyzer->data[i].minutes; }
}
return total;
}
#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);
/* Total minutes for topic; 0 for an absent or NULL topic. Reads only. */
long analyzer_topic_total(const Analyzer *analyzer, const char *topic);
#endif
Shell
reading after removal: 10Topic total checks passed
With the mutated loop, the reading == 35 assertion fails first: the last record, reading 10, is never visited. The function allocates nothing and writes nothing, so there is no failure path to test, only results. analyzer.c already includes <string.h> for the parser, so strcmp needs no new include. Browser edits are not saved in the download, so copy your three changes into the downloaded files below if you want to keep them.
Optional: run locally
Download the C text analyzer. The archive contains maintained sources, tests, sample input and a README. Browser edits are not included; copy your extension into the downloaded files to retain it.
Install a C17-capable Clang or GCC compiler (macOS Command Line Tools, a Linux compiler package, or Windows MSYS2). In a POSIX terminal inside the extracted folder:
Compile the two entrypoints separately and leave assertions enabled (do not define NDEBUG). Windows may add .exe to executable names; use the MSYS2 terminal for these shell commands. The browser's stdin and stdout correspond to terminal streams locally.
Going further
When your compiler supports them, add -g -fsanitize=address,undefined -fno-omit-frame-pointer to the test build and run it again. Use a debugger to stop at analyzer_append before a growth, inspect length/capacity, and step through the temporary-pointer commit. Sanitizer availability varies by local toolchain.
For a local file-stream extension, open a named file with fopen, check its result, pass the stream to a refactored import function and close it on every exit. Persistent files are optional local work; the core browser project remains stdin/stdout only.
Completion is saved in this browser only. It does not measure mastery.