file-handling · beginner · ~20 min
Safe bounded copy with a running pointer + remaining-capacity counter.
Implement size_t cat_buffers(const char **bufs, const size_t *lens, size_t n, char *out, size_t cap) that concatenates n buffers into out (up to cap bytes including a trailing NUL). Returns the total number of bytes written (not counting NUL). Truncates safely if cap would be exceeded.
cat looks trivial but the careful concatenation with bounds checking is a model for all 'copy bytes into a fixed buffer' patterns — the place where strncpy footguns kill projects.
Arrays bufs[n], lens[n]; out buffer of cap bytes.
Bytes written (excluding NUL). out is always NUL-terminated.
Cap >= 1. No malloc.
#include <stddef.h>
size_t cat_buffers(const char **bufs, const size_t *lens, size_t n, char *out, size_t cap) { /* TODO */ return 0; }
Forgetting the NUL byte in the budget; using strcat (re-scans every call — O(n^2)); writing one byte past the buffer.
cap == 1 (only the NUL fits). n == 0 (just NUL out). One buffer larger than cap (truncate).
O(total bytes).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.