Return to this page after a few days, and again about a week later. It is extra practice outside Day 7's time estimate. The delay is the point: pulling an idea back out of memory after you have started to forget it is what makes it stick, while rereading the implementation the same day mostly feels productive. Start every part with a blank editor or a blank sheet of paper, and only check the earlier lessons after you have committed to an answer.
Retrieve
Without looking, write two-octet big-endian read and write helpers, and one test that compares the encoder's output with bytes you derived by hand. Then explain, in two or three sentences, why writing sizeof(struct) raw bytes is not a wire format.
#include <stdio.h>
/* From memory: a two-octet big-endian read helper, a write helper, and one
test that compares the encoder's output with bytes you derived by hand. */
int main(void) {
return 0;
}Check your explanation
A complete answer mentions padding, host byte order, and the fact that alignment and effective-type rules make casting a byte buffer to a struct pointer undefined behavior.
Debug
Each scenario below violates one contract. Name the contract, predict the visible symptom, and say which test from the project would catch it. Reason about them on paper; do not run code that performs invalid memory accesses.
- A caller feeds the same bytes again after
FRAME_READY. - A parser writes
out->sensorbefore checking the checksum. - Reset clears
failedbut notused.
Check your answers
- It ignored
consumed. The symptom is a duplicated reading, and the next frame is decoded late or not at all. The chunk-size loop catches it, because it counts frames. - It published before validating. The symptom is a torn reading after an error. Every corruption test checks the sentinel
{77, 88}. - The new stream starts in the middle of an old frame, so the first frame after reset fails its header check. This is the manifest's "reset leaves partial count" mutation.
Transfer
Sketch, before coding, an opaque incremental decoder for a different bounded message type, for example a 12-byte GPS fix. Write down six decisions: who owns the input and for how long, how long the output stays valid, what consumed means for each status, what an empty feed does, what finish does at and away from a boundary, and what the recovery policy is after an error. If any answer is "it depends", the contract is not finished yet.
Predict and run
Read the program before pressing Run. Predict the number, then derive both octets for 4660 by hand and name the test that would catch a reversed byte order.
#include <stdio.h>
int main(void) {
unsigned char bytes[2] = {0x12,0x34};
unsigned long value = ((unsigned long)bytes[0] << 8) | bytes[1];
printf("%lu\n", value);
return 0;
}Check your prediction
46600x12 is 18, times 256 is 4608, plus 0x34, which is 52, gives 4660. Going back, 4660 >> 8 is 18 and 4660 & 0xFF is 52. A round trip cannot catch a reversed byte order if both directions share the mistake; a comparison with the hand-derived bytes 12 34 can.
Practice
Your turn
The caller's loop is the half of the streaming contract that the decoder cannot enforce. The starter gives a feed that follows the course's contract: at most one frame per call, an exact consumed, and a sticky error that consumes 0. From memory, write drain, which feeds a whole chunk and stops early only on an error. The starter's main must print:
chunk 1:
sensor 1
sensor 2
used 24 of 24
chunk 2:
error after 1 octets
used 1 of 1
chunk 3:
error after 0 octets
used 0 of 10#include <stdio.h>
typedef enum { NEED_MORE, FRAME_READY, DECODE_ERROR } Status;
typedef struct { Status status; size_t consumed; } FeedResult;
typedef struct { unsigned char frame[10]; size_t used; int failed; } Decoder;
/* At most one frame per call. On FRAME_READY, *sensor is the frame's sensor
and consumed counts that frame's octets; *sensor changes on no other path.
On DECODE_ERROR the decoder is failed: consumed counts up to and including
the bad octet, and while failed every call consumes 0. */
static FeedResult feed(Decoder *d, const unsigned char *bytes, size_t size, unsigned *sensor) {
FeedResult r = {NEED_MORE, 0};
if (d->failed) { r.status = DECODE_ERROR; return r; }
while (r.consumed < size) {
d->frame[d->used++] = bytes[r.consumed++];
int bad = (d->used == 1 && d->frame[0] != 0x54) ||
(d->used == 5 && (d->frame[1] != 1 || d->frame[2] != 1 || d->frame[3] != 0 || d->frame[4] != 4));
if (d->used == 10) {
unsigned char sum = 0;
for (size_t i = 0; i < 9; ++i) { sum = (unsigned char)(sum + d->frame[i]); }
bad = sum != d->frame[9];
}
if (bad) { d->failed = 1; r.status = DECODE_ERROR; return r; }
if (d->used == 10) {
*sensor = ((unsigned)d->frame[5] << 8) | d->frame[6];
d->used = 0; r.status = FRAME_READY; return r;
}
}
return r;
}
/* From memory: feed the whole chunk through feed, printing " sensor N" for each
frame and " error after N octets" on an error. Return the octets used. */
static size_t drain(Decoder *d, const unsigned char *chunk, size_t size) {
(void)d; (void)chunk; (void)size;
return 0;
}
int main(void) {
const unsigned char stream[25] = {
0x54, 1, 1, 0, 4, 0, 1, 0, 25, 0x74,
0x54, 1, 1, 0, 4, 0, 2, 0, 40, 0x84,
0x54, 1, 1, 0, 9};
Decoder d = {{0}, 0, 0};
printf("chunk 1:\n");
size_t used = drain(&d, stream, 24);
printf("used %zu of 24\n", used);
printf("chunk 2:\n");
used = drain(&d, stream + 24, 1);
printf("used %zu of 1\n", used);
printf("chunk 3:\n");
used = drain(&d, stream, 10);
printf("used %zu of 10\n", used);
return 0;
}Hint 1: the idea
Keep an offset into the chunk. Each call sees only the octets after it, the offset advances by exactly consumed, and the status decides whether to print and whether to go on.
Hint 2: a first step
Write the loop with the offset and the feed call, printing the sensor on FRAME_READY, and nothing for errors yet. Also count the loop's passes and stop after 20 with a stopped: no progress line, as Intermediate's grouping checkpoint did: a loop that trusts consumed alone can spin forever, and chunk 3 is where it would. Chunk 1 is now right. Then think about chunk 3: what does consumed become, and what happens to the offset?
Show one solution
#include <stdio.h>
typedef enum { NEED_MORE, FRAME_READY, DECODE_ERROR } Status;
typedef struct { Status status; size_t consumed; } FeedResult;
typedef struct { unsigned char frame[10]; size_t used; int failed; } Decoder;
/* At most one frame per call. On FRAME_READY, *sensor is the frame's sensor
and consumed counts that frame's octets; *sensor changes on no other path.
On DECODE_ERROR the decoder is failed: consumed counts up to and including
the bad octet, and while failed every call consumes 0. */
static FeedResult feed(Decoder *d, const unsigned char *bytes, size_t size, unsigned *sensor) {
FeedResult r = {NEED_MORE, 0};
if (d->failed) { r.status = DECODE_ERROR; return r; }
while (r.consumed < size) {
d->frame[d->used++] = bytes[r.consumed++];
int bad = (d->used == 1 && d->frame[0] != 0x54) ||
(d->used == 5 && (d->frame[1] != 1 || d->frame[2] != 1 || d->frame[3] != 0 || d->frame[4] != 4));
if (d->used == 10) {
unsigned char sum = 0;
for (size_t i = 0; i < 9; ++i) { sum = (unsigned char)(sum + d->frame[i]); }
bad = sum != d->frame[9];
}
if (bad) { d->failed = 1; r.status = DECODE_ERROR; return r; }
if (d->used == 10) {
*sensor = ((unsigned)d->frame[5] << 8) | d->frame[6];
d->used = 0; r.status = FRAME_READY; return r;
}
}
return r;
}
/* Feeds the whole chunk, printing each sensor. Returns the octets used;
stops early only on DECODE_ERROR. */
static size_t drain(Decoder *d, const unsigned char *chunk, size_t size) {
size_t offset = 0;
while (offset < size) {
unsigned sensor = 0;
FeedResult r = feed(d, chunk + offset, size - offset, &sensor);
offset += r.consumed;
if (r.status == FRAME_READY) { printf(" sensor %u\n", sensor); }
if (r.status == DECODE_ERROR) { printf(" error after %zu octets\n", offset); break; }
}
return offset;
}
int main(void) {
const unsigned char stream[25] = {
0x54, 1, 1, 0, 4, 0, 1, 0, 25, 0x74,
0x54, 1, 1, 0, 4, 0, 2, 0, 40, 0x84,
0x54, 1, 1, 0, 9};
Decoder d = {{0}, 0, 0};
printf("chunk 1:\n");
size_t used = drain(&d, stream, 24);
printf("used %zu of 24\n", used);
printf("chunk 2:\n");
used = drain(&d, stream + 24, 1);
printf("used %zu of 1\n", used);
printf("chunk 3:\n");
used = drain(&d, stream, 10);
printf("used %zu of 10\n", used);
return 0;
}chunk 1:
sensor 1
sensor 2
used 24 of 24
chunk 2:
error after 1 octets
used 1 of 1
chunk 3:
error after 0 octets
used 0 of 10Chunk 1 holds two frames and the first four octets of a third, and is used in full: the four octets wait inside the decoder. Chunk 2 completes that header with a length of 9, so the error comes after one octet. Chunk 3 is a perfectly valid frame, but the decoder is failed, so feed consumes nothing, and without the break the loop would call it forever with the same offset. That is why the status, not only consumed, must control the loop.
If any part of this page took more than a few minutes, that is useful information, not failure. Revisit Day 1 and the C intermediate allocator lessons if ownership felt uncertain, Day 2 if the shifts did, and Day 4 if the drain loop did. Operating-system sockets, concurrency, cryptographic protocols and unbounded formats are deliberately outside this course and deserve their own study.
Completion is saved in this browser only. It does not measure mastery.