A long-running program rarely creates a fresh decoder for every stream. It creates one, decodes a file, resets it, and decodes the next file with the same handle. That gives a handle two different "start over" operations, and confusing them causes real bugs:
- Reset returns an existing object to its initial logical state. The handle stays valid, its storage stays allocated, and the caller still owns it.
- Destroy ends the object's lifetime and releases its storage. The handle is dangling afterward.
A reset that frees the storage turns the caller's next call into a use-after-free. A reset that merely sets some pointer to NULL without freeing it leaks the allocation. A destroy that only resets fields leaks too. This checkpoint makes you write all three operations and prove they do what their names say.
Predict and run
Read the program before pressing Run. Write down its output and say which statement produces it.
#include <stdio.h>
typedef struct { size_t used; } State;
void reset(State *state) { state->used = 0; }
int main(void) {
State state = {4};
reset(&state);
reset(&state);
printf("%zu\n", state.used);
return 0;
}Check your prediction
0Reset is idempotent: calling it twice has the same effect as calling it once. That property is worth demanding, because cleanup code often cannot tell whether a reset already happened. Destroy is the opposite. Calling free twice on the same pointer is undefined behavior, so destroy must run exactly once per successful create.
The difference shows up clearly if reset is written wrong:
void tally_reset(Tally *tally) {
free(tally); /* wrong: reset must not end the lifetime */
}
/* caller */
tally_reset(tally);
tally_add(tally, 5); /* use after free */The caller did everything the API promised was allowed, yet its next call writes into freed memory. Under AddressSanitizer it stops with heap-use-after-free; without one it may appear to work. The correct reset touches only fields, so the address stays the same and stays valid:
#include <stdio.h>
#include <stdlib.h>
typedef struct { size_t used; int failed; } State;
void reset(State *state) { state->used = 0; state->failed = 0; }
int main(void) {
State *state = malloc(sizeof *state);
if (state == NULL) { return 1; }
state->used = 7; state->failed = 1;
State *before = state;
reset(state);
printf("Same handle: %s\n", before == state ? "yes" : "no");
printf("used %zu, failed %d\n", state->used, state->failed);
free(state);
return 0;
}Same handle: yes
used 0, failed 0What you already have
- An opaque type from the previous lessons:
typedef struct Tally Tally;before the definition, and a caller that uses only the declared operations. - The create and destroy contract from Creation and Destruction Contracts: create returns an initialized handle or
NULL, destroy acceptsNULL. - Idempotent reset from the top of this page: fields only, never the storage.
Plan before you type
The representation is yours this time; the starter gives only the declarations and the caller. Goals, not statements:
- Decide what a tally must remember to produce every report line, including
largest, and what "empty" means for each of those fields. - Decide how create and reset can share one definition of "empty", so a field added later cannot be initialized in one and forgotten in the other.
- Decide what each operation may assume about its argument, and which one must also accept
NULL. - Predict all four lines before you run, in particular "largest" after a reset and after the reused add.
Practice
Your turn
Build an opaque Tally that counts items, sums their amounts and remembers the largest amount added since the last reset. Implement the five declared operations; the starter's main is the caller and must not change. It must print:
After adds: 3 items, total 12, largest 5
After reset: 0 items, total 0, largest 0
After second reset: 0 items, total 0, largest 0
Reused: 1 items, total 2, largest 2#include <stdio.h>
#include <stdlib.h>
typedef struct Tally Tally;
Tally *tally_create(void);
void tally_add(Tally *tally, unsigned amount);
void tally_reset(Tally *tally);
void tally_report(const Tally *tally, const char *label);
void tally_destroy(Tally *tally);
/* Define struct Tally and the five operations here. */
int main(void) {
Tally *tally = tally_create();
if (tally == NULL) { return 1; }
tally_add(tally, 5); tally_add(tally, 3); tally_add(tally, 4);
tally_report(tally, "After adds");
tally_reset(tally);
tally_report(tally, "After reset");
tally_reset(tally);
tally_report(tally, "After second reset");
tally_add(tally, 2);
tally_report(tally, "Reused");
tally_destroy(tally);
tally_destroy(NULL);
return 0;
}Hint 1: the idea
Reset is the definition of "initial state". If create calls reset after a successful allocation, the two can never disagree about what a fresh tally looks like, and every field you add later is initialized in one place.
Hint 2: a first step
Write the struct and tally_report first, then a create that allocates and checks for NULL, and a destroy. Stub add and reset with empty bodies and run: whatever the first line prints tells you whether create really produced the empty state, or only got lucky with what malloc returned.
Show one solution
#include <stdio.h>
#include <stdlib.h>
typedef struct Tally Tally;
Tally *tally_create(void);
void tally_add(Tally *tally, unsigned amount);
void tally_reset(Tally *tally);
void tally_report(const Tally *tally, const char *label);
void tally_destroy(Tally *tally);
struct Tally { size_t items; unsigned total; unsigned largest; };
Tally *tally_create(void) {
Tally *tally = malloc(sizeof *tally);
if (tally != NULL) { tally_reset(tally); }
return tally;
}
void tally_add(Tally *tally, unsigned amount) {
++tally->items;
tally->total += amount;
if (amount > tally->largest) { tally->largest = amount; }
}
void tally_reset(Tally *tally) { tally->items = 0; tally->total = 0; tally->largest = 0; }
void tally_report(const Tally *tally, const char *label) {
printf("%s: %zu items, total %u, largest %u\n", label, tally->items, tally->total, tally->largest);
}
void tally_destroy(Tally *tally) { free(tally); }
int main(void) {
Tally *tally = tally_create();
if (tally == NULL) { return 1; }
tally_add(tally, 5); tally_add(tally, 3); tally_add(tally, 4);
tally_report(tally, "After adds");
tally_reset(tally);
tally_report(tally, "After reset");
tally_reset(tally);
tally_report(tally, "After second reset");
tally_add(tally, 2);
tally_report(tally, "Reused");
tally_destroy(tally);
tally_destroy(NULL);
return 0;
}After adds: 3 items, total 12, largest 5
After reset: 0 items, total 0, largest 0
After second reset: 0 items, total 0, largest 0
Reused: 1 items, total 2, largest 2One malloc and one free bracket the whole program, no matter how many resets happen in between, and tally_destroy(NULL) is harmless because free(NULL) is. largest is the field that tests the design: it is easy to add to the struct and to add, and easy to forget in reset. The project's decoder_create uses the same trick: it calls decoder_reset so creation and reset share one definition of the empty state. Day 2 moves from the handle to the bytes it will decode.
Prove it can fail
Once your output matches, break reset on purpose: make it clear items and total but forget largest. Both reset lines now say largest 5, and the "Reused" line says total 2, largest 5, which is impossible for a stream holding one item of 2. That is the bug of two unrelated streams bleeding into each other. Restore it, then delete the tally_destroy(tally); line and, if your native compiler supports it, build with -fsanitize=address. LeakSanitizer reports one leaked allocation of the struct's size when the program exits.
Mistakes worth checking for
- The first report shows a garbage value. Create allocated the struct but did not initialize every field, because
mallocdoes not zero memory. Calling reset from create avoids this. - A crash or sanitizer report on the call after reset. Reset freed the handle. Reset must change fields only.
- A stale
largestafter reset. Reset cleared only some fields, so old state leaked into the new stream. - A crash at the end of
main. The program destroyed the handle twice, or destroy does not acceptNULL. - The caller reads
tally->totaldirectly. That only compiles because the definition is in the same file. In a split library it would be an incomplete-type error; use the report function.
Completion is saved in this browser only. It does not measure mastery.