linux-sysprog · beginner · ~20 min

Return the last N bytes of a buffer (tail)

Compute the right slice offset; bound-check the copy.

Challenge

Implement size_t tail_bytes(const char *buf, size_t n, char *out, size_t cap, size_t want) that copies the last want bytes of buf (or all of buf if want > n) into out (capped at cap - 1, NUL-terminated). Returns the number of bytes copied.

Why this matters

tail is fundamental to log viewing. The byte-mode kernel is just 'last N bytes' — and 'last N lines' is built on top of it.

Input format

buf/n source; out/cap destination; want bytes.

Output format

Bytes copied; out NUL-terminated.

Constraints

No allocations.

Starter code

#include <stddef.h>
size_t tail_bytes(const char *buf, size_t n, char *out, size_t cap, size_t want) { /* TODO */ return 0; }

Common mistakes

Computing start = n - want when want > n → underflow on size_t; not reserving the NUL byte in cap.

Edge cases to handle

want == 0 → out is empty string. want > n → copy entire buf. cap == 1 → only NUL fits.

Complexity

O(want).

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.