file-handling · intermediate · ~12 min
Bounds-checked indexing into a fixed-record buffer.
#include <stdint.h>
#include <stddef.h>
int read_record(const uint8_t *buf, size_t n, size_t recsize, int idx, unsigned char *out);
Copy the idx-th recsize-byte record from buf into out. Return 0 on
success, or -1 on NULL, recsize == 0, negative idx, or a record that runs
past n.
idx * recsize.start + recsize <= n before copying.Binary formats (databases, MFT, packet logs) are arrays of fixed-size records; reading record N is just bounds-checked indexing.
#include <stdint.h>
#include <stddef.h>
int read_record(const uint8_t *buf, size_t n, size_t recsize, int idx, unsigned char *out) {
/* TODO */
(void)buf; (void)n; (void)recsize; (void)idx; (void)out;
return -1;
}
Integer overflow on idx×recsize (guard with the bound check). Off-by-one letting the last record read past n.
Last valid record. idx one past the end. recsize 0.
O(recsize).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.