Skip to content

Assemble the Analyzer

The Course
•
35 min study

Each piece of the analyzer is something you have already built: a bounded line reader (Day 4), a record parser that commits only on success (Day 4), a growing collection with a failure-safe append (Day 3), a sorted, grouped report (Day 5), and one cleanup path (Day 6). This lesson follows a line of input through all of them, so that when you open the source you can say why each line is there. Read with three questions in mind: who owns this memory, what happens if this call fails, and how long is this pointer valid?

Predict and run

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

Predict before running C
#include <stdio.h>

int main(void) {
    int minutes[] = {25, 0, 181, 40, 180};
    size_t accepted = 0, rejected = 0;
    for (size_t i = 0; i < sizeof minutes / sizeof minutes[0]; ++i) {
        if (minutes[i] >= 1 && minutes[i] <= 180) {
            ++accepted;
        } else {
            ++rejected;
        }
    }
    printf("Accepted: %zu, rejected: %zu\n", accepted, rejected);
    printf("Processed: %zu\n", accepted + rejected);
    return 0;
}
Check your prediction
Text
Accepted: 3, rejected: 2
Processed: 5

0 and 181 fall outside 1 to 180, and 180 itself is inside, so three values are accepted. This is the accounting rule for the whole program: every input line ends up in exactly one of the two counts. If accepted plus rejected ever differs from the number of lines, some path counted a line twice or not at all.

The path of one line

main.c owns a 96-byte line buffer, a rejected counter and one Analyzer. For each line:

  1. fgets fills the buffer. If there is no newline and the stream is not at its end, the line is too long: drain it, count one rejection, continue.
  2. record_parse(line, &record) validates into a local candidate and copies it to record only on success. On ANALYZER_INVALID, count a rejection and continue.
  3. analyzer_append(&analyzer, &record) copies the record into owned storage, growing if needed. ANALYZER_FULL and ANALYZER_INVALID are rejections. ANALYZER_NOMEM is fatal.

After the loop, main checks ferror(stdin), calls analyzer_report, prints the summary from analyzer.length and analyzer_total, and checks ferror(stdout). record lives on the stack and is reused on every iteration; that is safe because analyzer_append copies it by value.

Ownership, from init to destroy

analyzer_init sets data to NULL and both counts to 0, and stores the allocator. From then on, analyzer.data is owned by the analyzer and changed only by its functions. Growth replaces it through a temporary after resize succeeds. The report allocates a second, temporary block, copies the records into it, sorts and prints it, and releases it before returning: that block's whole lifetime is inside one function call. At cleanup:, analyzer_destroy releases data and resets the fields. So the program holds at most two blocks at once, and both are released on every path.

The append detail that is easy to miss

Read this part of analyzer_append:

C
/* A caller may pass &data[i]. Copy it before realloc can invalidate it. */
Record candidate = *record;
if (analyzer->length == analyzer->capacity) {
    /* ... resize, which may move data ... */
}
analyzer->data[analyzer->length] = candidate;

main never passes a pointer into the collection, so ordinary runs would work without the copy. But the header promises the function "copies record by value", and a caller duplicating an existing record would write analyzer_append(&a, &a.data[0]). If growth moved the block, reading *record afterward would be a use-after-free. Copying first makes the promise true for every caller, and test_analyzer.c checks exactly this call across a growth.

Rejected versus fatal

A rejected record is the input's problem: the program can report it and keep going, and the result is still a correct report of the valid lines. Out of memory is the program's problem: it can no longer store what the user gave it, so any report would silently leave records out. That is why main treats ANALYZER_NOMEM differently from every other status. The library only reports the status; the policy lives in main.

Practice

Exercise

Your turn

Write Action decide(Status status) that maps STATUS_OK to ACTION_COUNT_ACCEPTED, STATUS_INVALID and STATUS_FULL to ACTION_COUNT_REJECTED, and STATUS_NOMEM to ACTION_STOP. The starter simulates a run over a list of statuses and stops at the first ACTION_STOP. Expected output: accepted 2, rejected 2, stopped: yes.

Your workspace C
#include <stdio.h>
#include <stddef.h>

typedef enum { STATUS_OK, STATUS_INVALID, STATUS_FULL, STATUS_NOMEM } Status;
typedef enum { ACTION_COUNT_ACCEPTED, ACTION_COUNT_REJECTED, ACTION_STOP } Action;

/* Write decide here. */

int main(void) {
    Status results[6] = {STATUS_OK, STATUS_INVALID, STATUS_OK, STATUS_FULL, STATUS_NOMEM, STATUS_OK};
    size_t accepted = 0, rejected = 0;
    int stopped = 0;
    for (size_t i = 0; i < 6 && !stopped; ++i) {
        switch (decide(results[i])) {
        case ACTION_COUNT_ACCEPTED: ++accepted; break;
        case ACTION_COUNT_REJECTED: ++rejected; break;
        case ACTION_STOP: stopped = 1; break;
        }
    }
    printf("accepted %zu, rejected %zu, stopped: %s\n", accepted, rejected, stopped ? "yes" : "no");
    return 0;
}
Hint 1: the idea

The last STATUS_OK comes after the out-of-memory result, so it must never be counted. Stopping is a decision about the rest of the input, not about one line.

Hint 2: a first step

List the four statuses and the action each one maps to on paper first, then write decide as a switch with one case per status. Leave out default and ask why: what should the compiler say if a fifth status is added to the enum later?

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

typedef enum { STATUS_OK, STATUS_INVALID, STATUS_FULL, STATUS_NOMEM } Status;
typedef enum { ACTION_COUNT_ACCEPTED, ACTION_COUNT_REJECTED, ACTION_STOP } Action;

Action decide(Status status) {
    switch (status) {
    case STATUS_OK: return ACTION_COUNT_ACCEPTED;
    case STATUS_INVALID:
    case STATUS_FULL: return ACTION_COUNT_REJECTED;
    case STATUS_NOMEM: return ACTION_STOP;
    }
    return ACTION_STOP;
}

int main(void) {
    Status results[6] = {STATUS_OK, STATUS_INVALID, STATUS_OK, STATUS_FULL, STATUS_NOMEM, STATUS_OK};
    size_t accepted = 0, rejected = 0;
    int stopped = 0;
    for (size_t i = 0; i < 6 && !stopped; ++i) {
        switch (decide(results[i])) {
        case ACTION_COUNT_ACCEPTED: ++accepted; break;
        case ACTION_COUNT_REJECTED: ++rejected; break;
        case ACTION_STOP: stopped = 1; break;
        }
    }
    printf("accepted %zu, rejected %zu, stopped: %s\n", accepted, rejected, stopped ? "yes" : "no");
    return 0;
}
Text
accepted 2, rejected 2, stopped: yes

Two empty cases in a row are deliberate sharing, not an accidental fall-through: no statement sits between them. An unknown value falls back to ACTION_STOP, the safe choice when the program cannot tell what happened. The real main does the same with goto cleanup. Now run the complete application.

Run the complete application

The input box is prefilled with the sample from the brief.

Text analyzer C
#include "analyzer.h" #include <stdio.h> #include <string.h> int main(void) { Analyzer analyzer; analyzer_init(&analyzer, analyzer_default_allocator()); size_t rejected = 0; int exit_code = 1; char line[96]; while (fgets(line, sizeof line, stdin) != NULL) { if (strchr(line, '\n') == NULL && !feof(stdin)) { int ch; while ((ch = getchar()) != '\n' && ch != EOF) { } ++rejected; continue; } Record record; if (record_parse(line, &record) != ANALYZER_OK) { ++rejected; continue; } AnalyzerStatus status = analyzer_append(&analyzer, &record); if (status == ANALYZER_NOMEM) { fprintf(stderr, "Storage unavailable\n"); goto cleanup; } if (status != ANALYZER_OK) { ++rejected; } } if (ferror(stdin)) { fprintf(stderr, "Input error\n"); goto cleanup; } if (analyzer_report(&analyzer, stdout) != ANALYZER_OK) { fprintf(stderr, "Report storage unavailable\n"); goto cleanup; } printf("Accepted: %zu\nTotal: %ld minutes\nRejected: %zu\n", analyzer.length, analyzer_total(&analyzer), rejected); if (ferror(stdout)) { goto cleanup; } exit_code = 0; cleanup: analyzer_destroy(&analyzer); return exit_code; } #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 reading 25 coding 40 bad reading 10 coding 0
Check your prediction
Text
coding: 1 sessions, 40 minutes
reading: 2 sessions, 35 minutes
Accepted: 3
Total: 75 minutes
Rejected: 2

Then try these inputs and predict each report before running: an empty input box (No records and three zeros); reading 25, a bad line and coding 40 (both valid records, sorted by topic, one rejection); and an overlong line followed by reading 25. The long line must count as exactly one rejection, and the next line must still be read.

Was this article helpful?

Your response is saved on this device.