Bounded snprintf & Safe Text Parsing

Unchecked pos += snprintf(buf + pos, cap - pos, ...) loops wrap unsigned capacities into massive heap overruns on truncation, while fscanf("%s") overflows buffers and wedges streams on malformed lines. You will master portable <inttypes.h> formatting, deterministic snprintf() truncation math, and line-isolated fgets() + strtol() parsers.

20 minfree previewLinux 6.12C11glibc 2.39→ module 5 lab
What you'll learn
  • Format fixed-width and pointer-sized integers portably (%zu, PRId64, PRIu64) via snprintf() with -Wformat clean.
  • Detect formatted output truncation deterministically by checking ret < 0 || (size_t)ret >= size on every snprintf().
  • Construct fault-isolated text parsers combining line-bounded fgets(), width-capped scansets, and ERANGE strtol().

Why Unchecked snprintf Accumulators & Raw fscanf Cause Exploits

Most C engineers know sprintf() is banned—yet a subtle snprintf() anti-pattern causes buffer overflows in production codebases every year! A developer writes a multi-field log builder size_t pos = 0; pos += snprintf(buf + pos, sizeof(buf) - pos, ...); repeated three times without checking each return value: when Call 1 needs 80 bytes in a 64-byte buf, snprintf() safely caps its write at 63 chars + '\0', but returns 80! Now pos equals 80, sizeof(buf) - pos (64U - 80U) wraps unsigned size_t to 18,446,744,073,709,551,600, and Call 2 blasts uninhibited across the stack! On the input side, fscanf(fp, "%s=%d", key, &val) overflows key on long tokens and leaves non-numeric garbage wedged in fp forever!

Bulletproof text formatting and parsing in C11 rest on three rules: checking snprintf()'s hypothetical-length return contract on every call, matching <inttypes.h>/%zu specifiers across 32/64-bit ABIs, and decoupling line framing (fgets) from in-memory token validation (sscanf width-capped scansets + strtol ERANGE).

note: Calling sprintf() is like pouring hot metal into a mold with no overflow lip, whereas snprintf() caps the pour at the rim and reports the exact volume that would have filled an uncapped mold.

Where it stops working: Overflowed metal spills visibly onto the shop floor, whereas snprintf() silently truncates excess characters unless the caller checks whether the returned length is greater than or equal to the buffer capacity.

definition (Bounded snprintf(), <inttypes.h> Macros & Scanset Framing): snprintf(buf, size, fmt, ...) Return Contract (ISO C99/C11 §7.21.6.5): Writes at most size - 1 characters plus a guaranteed terminating '\0' (whenever size > 0), and returns int ret equal to the character count that would have been written excluding '\0' (ret < 0 on encoding error; (size_t)ret >= size if and only if output was truncated). Fixed-Width Format Macros (PRIu64, PRId64): String-literal macros in <inttypes.h> concatenated at compile time ("lu" on LP64 x86-64 vs "llu" on ILP32 ARMv7) so -Wformat -Werror stays clean across ABIs.

One Layer Down: Safe Buffer-Append Algebra & Off-by-One Scanset Widths

To append multiple formatted segments into char buf[CAP] at cursor size_t pos (0 <= pos < CAP), let remaining capacity be R = CAP - pos. After int n = snprintf(buf + pos, R, fmt, ...), full non-truncated fit holds if and only if n >= 0 && (size_t)n < R. Only when both inequalities hold may pos advance to pos + (size_t)n (preserving pos <= CAP - 1). Conversely, if you want dynamic exact-fit allocation, probe with int need = snprintf(NULL, 0U, fmt, ...);, check need >= 0, allocate (size_t)need + 1U bytes via malloc(), and format once with zero wasted memory!

On input, notice the critical 1-byte asymmetry between fgets() and sscanf() width specifiers for char tag[16]: fgets(tag, 16, fp) includes the '\0' inside 16 (reading at most 15 payload bytes), whereas sscanf(line, "%15[^=]", tag) specifies maximum payload characters excluding '\0' (15 chars + 1 '\0' = 16 bytes; writing %16[^=] overflows tag[16] by 1 byte!).

Formatter / Parser ToolExact C11 / POSIX IdiomSafety & ABI Guarantee
snprintf(buf, sz, ...)Reject if `ret < 0 \\(size_t)ret >= sz`Never writes past sz; detects every 1-byte truncation
dprintf(fd, fmt, ...)Direct POSIX descriptor formattingEmits formatted text straight to fd without a FILE *
%zu / %zd & PRIu64"sz=%zu ts=%" PRIu64 (<inttypes.h>)Zero -Wformat warnings on both 32-bit ARMv7 and 64-bit x86-64
fgets(line, sizeof(line), fp)Drain to '\n' if line[len-1] != '\n'Isolates corrupt/oversized lines so next line starts cleanly
%15[^=]=%31[^\n] + strtolWidth = sizeof(dst) - 1; check ERANGE & *endp == '\0'Prevents buffer overflow and rejects "12abc" or LONG_MAX overflow
fig_m05_l03_arch.svg — Truncation-checked snprintf() accumulator math,…

Figure 5.3. Truncation-checked snprintf() accumulator math, <inttypes.h> specifiers, and fault-isolated fgets() + strtol() parsing.

step_m05_l03.svg — Check (size_t)ret < rem before advancing snprintf()…step 1/4
  1. Step 1. Frame bounded lines with fgets(line, sizeof(line), fp) and check ferror(fp) vs feof(fp) on NULL exit.
  2. Step 2. When line[len - 1] != '\\n' before EOF, drain excess bytes up to '\\n' via int fgetc(fp) to quarantine oversized lines.
  3. Step 3. Split key=value fields with width sizeof(dst) - 1 (%15[^=] for char[16]) so '\\0' never overflows.
  4. Step 4. Validate numeric ranges via strtol() (ERANGE and *endp == '\\0') and guard snprintf() with (size_t)ret < rem.

Figure 5.3b. Check (size_t)ret < rem before advancing snprintf() cursors, and isolate line framing with fgets() before tokenizing via (sizeof - 1) scansets and strtol().

<inttypes.h> Specifiers, dprintf(3) & strtol(3) Validation

Include <stdio.h>, <stdlib.h>, <inttypes.h>, <stdint.h>, <limits.h>, and <errno.h> under #define _POSIX_C_SOURCE 200809L. Remember why atoi() is unusable in systems code: atoi("garbage") returns 0 (indistinguishable from "0"!) and invokes Undefined Behavior on integer overflow, whereas errno = 0; long v = strtol(s, &endp, 10); flags empty strings (endp == s), trailing junk (*endp != '\0'), and range saturation (errno == ERANGE).

Building a Truncation-Checked Formatter & Fault-Isolated Line Parser

Save fmt_safe_codec.c below. It emits valid, malformed, oversized, and overflowing sensor lines via dprintf(fd, ...), verifies snprintf() truncation detection (req=28 >= cap=16, trunc=1) plus safe multi-step buf_appendf(), and runs a line-isolated fgets() + %15[^=]=%31[^\n] + strtol() parser that drains an oversized line and rejects malformed/ERANGE inputs without losing the valid records that follow!

learner@ksa: ~/gl-c01/m05-l03
learner@ksa:~/gl-c01/m05-l03$ bat -H 16 -H 36 -H 48 -H 59 fmt_safe_codec.c File: fmt_safe_codec.c    #define _POSIX_C_SOURCE 200809L    #include <errno.h>    #include <fcntl.h>    #include <inttypes.h>    #include <limits.h>    #include <stdarg.h>    #include <stdint.h>    #include <stdio.h>    #include <stdlib.h>    #include <string.h>    #include <unistd.h>        static int buf_appendf(char *buf, size_t cap, size_t *pos,                           const char *fmt, ...) {        if (*pos >= cap) return -1;      size_t rem = cap - *pos;        va_list ap;        va_start(ap, fmt);        int ret = vsnprintf(buf + *pos, rem, fmt, ap);        va_end(ap);        if (ret < 0 || (size_t)ret >= rem) return -1;        *pos += (size_t)ret;        return 0;    }        int main(void) {        const char *path = "/tmp/ksa_m05_l03.txt";        int fd = open(path, O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC, 0644);        if (fd < 0) return 1;            uint64_t ts = 9000000001ULL;        size_t idx = 4U;        if (dprintf(fd, "rail_a=%+06d\nbad_line_no_eq\n"                        "oversized_sensor_tag_abcdefghijklmnopqrstuvwxyz0123456789=10\n"                        "rail_b=999999999999999999999\nvcore_mv=-125\n",                  3300) < 0) return 1;        (void)close(fd);            char small[16];        volatile size_t cap = sizeof(small);        int req = snprintf(small, cap, "ts=%" PRIu64 " idx=%zu hex=%#x",                           ts, idx, 255U);        int trunc_detected = (req < 0 || (size_t)req >= cap) ? 1 : 0;            char accum[20];        size_t apos = 0U;        int app_ok = (buf_appendf(accum, sizeof(accum), &apos, "id=%u ", 7U) == 0 &&                    buf_appendf(accum, sizeof(accum), &apos,                                  "overflow_tail_999999") == -1);        printf("snprintf_check: req=%d cap=%zu trunc=%d app_guard=%d prefix=%s\n",               req, (size_t)cap, trunc_detected, app_ok, small);            FILE *fp = fopen(path, "re");        if (!fp) return 1;        char line[48];        unsigned int ok = 0U, bad = 0U;        long sum_mv = 0L;        while (fgets(line, sizeof(line), fp) != NULL) {            size_t len = strlen(line);            if (len > 0U && line[len - 1U] != '\n' && !feof(fp)) {                int ch;                while ((ch = fgetc(fp)) != '\n' && ch != EOF) {}                bad++;                continue;            }            char tag[16], num_s[32];            if (sscanf(line, "%15[^=]=%31[^\n]", tag, num_s) != 2) {                bad++;                continue;            }            char *endp = NULL;            errno = 0;            long val = strtol(num_s, &endp, 10);            if (errno == ERANGE || endp == num_s || *endp != '\0' ||                val < INT_MIN || val > INT_MAX) {                bad++;                continue;            }            ok++;            sum_mv += val;        }        int clean_end = (!ferror(fp) && feof(fp)) ? 1 : 0;        if (fclose(fp) != 0 || !clean_end) return 1;        (void)unlink(path);            printf("parser_check: ok=%u bad=%u sum_mv=%ld\n", ok, bad, sum_mv);        return 0;    }
  1. Guard ret < 0 || (size_t)ret >= rem BEFORE advancing *pos so a truncated snprintf() never wraps cap - *pos.
  2. Drain remaining characters up to '\n' when an oversized line lacks a newline so its tail cannot masquerade as the next record.
  3. Use width sizeof(buf) - 1 (%15[^=] for char[16]) and verify errno != ERANGE && endp != num_s && *endp == '\0'.

Verifying Truncation Math, Oversized-Line Draining & Lab 5

Compile and execute fmt_safe_codec: confirm req=28 vs cap=16 (trunc=1, app_guard=1), confirm parser_check isolates all 3 bad lines (no_eq, oversized, and ERANGE overflow -> bad=3) while recovering rail_a=+03300 and vcore_mv=-125 (ok=2, sum_mv=3175), and complete lab_m05_telemetry_codec.

learner@ksa: ~/gl-c01/m05-l03
learner@ksa:~/gl-c01/m05-l03gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror fmt_safe_codec.c -o fmt_safe_codeclearner@ksa:~/gl-c01/m05-l03./fmt_safe_codecsnprintf_check: req=28 cap=16 trunc=1 app_guard=1 prefix=ts=9000000001 iparser_check: ok=2 bad=3 sum_mv=3175learner@ksa:~/gl-c01/m05-l03test ! -e /tmp/ksa_m05_l03.txt && rm -f fmt_safe_codeclearner@ksa:~/gl-c01/m05-l03

Lab 5: Bounded stdio Sensor Log Parser & Binary Codec

env: host

1. Motivation

Telemetry ingestion pipelines sit directly on the untrusted boundary between noisy serial/CSV text feeds and compact binary storage files. Naive fscanf(in, "%s,%u,%d") parsers suffer buffer overflows on long sensor IDs and wedge permanently when a single corrupted UART line arrives, while while (!feof(fp)) readers duplicate the final binary sample and unchecked snprintf() calls silently truncate diagnostic summaries. In this lab, you will build telemetry_codec to master line-isolated fgets() + strtoul()/strtol() ingestion, batched item-counted fwrite()/fread(), torn-tail detection via ftello(), and deterministic snprintf() truncation checks.

2. Learning Objectives

  1. Ingest untrusted CSV sensor streams via bounded fgets() (draining > 127-byte oversized lines up to '\n') and validate <id>,<seq>,<mv> fields with strtoul()/strtol() (ERANGE and character-set guards).
  2. Serialize 24-byte struct sensor_frame batches (16 records per fwrite() call) onto "wbe" streams with checked ferror() and fclose().
  3. Inspect binary streams via while (fread(&frame, sizeof(frame), 1, fp) == 1) (never while (!feof(fp))), detecting partial trailing bytes (exit 2) via ftello()/fseeko().
  4. Enforce snprintf(buf, cap, ...) bounds by detecting needed < 0 || (size_t)needed >= cap (exit 3).

3. Environment Requirements

  • Host Execution Environment (Tested): Linux 6.12 LTS (x86_64, glibc 2.39+), #define _POSIX_C_SOURCE 200809L and #define _FILE_OFFSET_BITS 64.
  • Target Board Portability (ARMv7 Cortex-A7): struct sensor_frame (char id[16]; uint32_t seq; int32_t mv;) has natural 4-byte alignment and 0 padding bytes (sizeof == 24) across both 32-bit ARMv7 and 64-bit x86_64 little-endian targets, and int ch = fgetc(in) avoids the unsigned-char ARMv7 infinite loop during line draining!

4. Required Software & Hardware

  • Software Toolchain: gcc (-std=c11 -Wall -Wextra -Werror), strace, truncate, and /bin/sh.
  • Hardware: Standard Linux host environment.

5. Complete Executable Commands

Run from labs/lab_m05_telemetry_codec/:

learner@ksa: ~/gl-c01/m05-l03
learner@ksa:~/gl-c01/m05-l03$ bat script.sh File: script.sh    # 1. Compile the warning-clean sensor parser and binary codec    gcc -std=c11 -O2 -Wall -Wextra -Werror files/telemetry_codec.c -o /tmp/telemetry_codec        # 2. Create a mixed CSV feed (valid rows, comments, ERANGE overflow, and >128B oversized line)    python3 -c '    print("# boot log\nvcore,1,1150\nmalformed_row\n" + "x"*150 + ",2,100\npll_mv,2,1800\nbad_ovf,999999999999,10\nvcore,3,1120")    ' > /tmp/ksa_sensors.csv        # 3. Encode valid rows to binary (3 valid * 24B = 72B, 3 rejected) and inspect with sufficient cap    /tmp/telemetry_codec encode /tmp/ksa_sensors.csv /tmp/ksa_sensors.bin    /tmp/telemetry_codec inspect /tmp/ksa_sensors.bin 64        # 4. Test deterministic snprintf() truncation (cap=16 -> exit 3) and torn-tail detection (exit 2)    /tmp/telemetry_codec inspect /tmp/ksa_sensors.bin 16; echo "trunc_rc=$?"    printf 'TORN!' >> /tmp/ksa_sensors.bin    /tmp/telemetry_codec inspect /tmp/ksa_sensors.bin 64; echo "torn_rc=$?"        # 5. Clean up and run the full TAP 13 verification harness    rm -f /tmp/telemetry_codec /tmp/ksa_sensors.csv /tmp/ksa_sensors.bin    sh check.sh

*Why each command runs:* Step 2 injects every real-world CSV fault (# comments, missing commas, 150-char line overflow, UINT32_MAX overflow); Step 3 proves the parser isolates all 3 bad lines and recovers vcore,3,1120; Step 4 verifies exit 3 on cap=16 truncation and exit 2 (PARTIAL_TAIL bytes=5) on a torn binary tail; and Step 5 runs sh check.sh.

6. Annotated Source Code (starter/ Flaws vs files/ Reference)

Flawed Baseline (starter/telemetry_codec.c)

  1. Wedging fscanf() (encode): while (fscanf(in, "%15[^,],%u,%d\n", ...) == 3) halts at the very first malformed or # comment line (valid=0 or partial output) and silently wraps overflowing integers!
  2. Off-by-one while (!feof(fp)) (inspect): Runs an extra loop iteration at EOF, counting VALID=4 on a 3-record file!
  3. Missing torn-tail & snprintf() checks: Ignores partial trailing bytes (PARTIAL_TAIL) and prints silently truncated strings with exit 0.

Warning-Clean Reference (files/telemetry_codec.c)

  • Oversized-Line Drain (cmd_encode): Checks if (len > 0 && line[len - 1] != '\n' && !feof(in)) and drains via int ch; while ((ch = fgetc(in)) != '\n' && ch != EOF) {} before incrementing rejected, keeping the next line cleanly aligned!
  • Strict Token Validation (parse_csv_line): Rejects leading '-' before strtoul() (because strtoul("-1", ...) legally wraps modulo ULONG_MAX!), checks errno == 0 && *end_seq == ',' && seq_ul <= UINT32_MAX, and checks mv_l in [-100000, 100000].
  • Torn-Tail & Truncation Guards (cmd_inspect): Snapshots pos_before = ftello(fp) prior to each fread(&frame, 24, 1, fp), compares SEEK_END end_pos > pos_before (exit 2), and checks needed < 0 || (size_t)needed >= cap (exit 3).

7. Expected Output

learner@ksa: ~/gl-c01/m05-l03
learner@ksa:~/gl-c01/m05-l03$ bat listing.txt File: listing.txt    $ sh check.sh    TAP version 13    1..5    ok 1 - builds cleanly with -std=c11 -Wall -Wextra -Werror    ok 2 - encodes valid CSV rows into 24-byte frames while isolating malformed and >128B lines    ok 3 - reads exact record count without while(!feof) off-by-one duplication    ok 4 - detects torn trailing binary bytes via ftello/fseeko (exit 2)    ok 5 - detects snprintf summary buffer truncation deterministically (exit 3)    # pass 5/5

8. Explanation of Observed Behavior

Batching 16 struct sensor_frame items (16 * 24 = 384 bytes) into fwrite() copies records inside glibc's Ring 3 _IO_FILE buffer, emitting just 1 write() syscall when fclose(out) flushes a 72-byte or 6,144-byte batch. On inspection of the 77-byte torn file (72 + 5), Iteration 4 records pos_before = 72, fread(&frame, 24, 1, fp) consumes the 5 torn bytes, hits EOF, sets _IO_EOF_SEEN, and returns 0 complete items; fseeko(fp, 0, SEEK_END) + ftello(fp) then measures end_pos = 77 > 72, reporting PARTIAL_TAIL bytes=5 (exit 2)!

9. Experiment Variations

  1. strtoul("-5") Sign-Wrap Experiment: Comment out if (!isdigit((unsigned char)*s_seq)) return -1; in a scratch copy and pass vcore,-1,3300 on 64-bit Linux to observe strtoul() parse -1 as 18446744073709551615UL (> UINT32_MAX), and pass vcore,-1,3300 on 32-bit ILP32 where ULONG_MAX == UINT32_MAX (4294967295 accepted silently without the isdigit guard!).
  2. strace Batching Verification: Encode 1,000 CSV rows (24,000 bytes) under strace -e trace=read,write and confirm glibc's 8 KiB _IOFBF buffer reduces 1,000 logical records to 3 write() syscalls!
  3. In-Memory Fuzzing via fmemopen: Refactor cmd_encode into encode_streams(FILE *in, FILE *out) and fuzz parse_csv_line in memory using fmemopen() + open_memstream() under -fsanitize=address,undefined.

10. Performance Measurements

Measured on Host x86_64 Linux 6.12 LTS (CLOCK_MONOTONIC, 5 warmup runs, N = 35 end-to-end encode + inspect cycles over 256 CSV rows = 6,144 binary bytes):

MetricMeasured Host (x86_64 Linux 6.12)Target Board Expectation (ARMv7 Cortex-A7)
256-row encode + inspect (p50 / p95 / p99)3,829.6 us / 4,709.7 us / 5,941.2 us~14,000–21,000 us (2 CLI spawns; < 180 us in-process codec)
Kernel write() syscalls for 256 rows (6,144 B)1 (< 8 KiB _IOFBF buffer flushed at fclose)1 (_IOFBF 4 KiB or 8 KiB -> 1–2 write traps)

11. Troubleshooting

SymptomRoot CauseFix
VALID is N + 1 on every clean binary fileUsed while (!feof(fp)) instead of checking fread() == 1Loop on while (fread(&frame, sizeof(frame), 1, fp) == 1)
Infinite loop on ARMv7 when draining > 128B CSV lineStored fgetc(in) in char ch (unsigned char 255 != -1 EOF)Declare int ch; for fgetc(in)
Negative sequence -1 accepted on 32-bit targetsstrtoul() allows leading '-' and negates modulo ULONG_MAXCheck isdigit((unsigned char)*s_seq) before strtoul()
-Wsign-compare or -Wformat error on size_tPrinted size_t with %lu instead of %zuUse %zu for size_t across 32/64-bit builds

12. Guided Questions

  1. Why must valid_id_char((unsigned char)line[i]) cast char to unsigned char before calling <ctype.h> isalnum()?
  • *Hint 1:* Check man 3 isalnum for the exact input domain required by ISO C11 <ctype.h> functions (unsigned char widened to int, or EOF).
  • *Hint 2:* On x86-64 (signed char), what negative int value is passed to isalnum() if an untrusted UTF-8 byte 0xC3 arrives without the (unsigned char) cast (Undefined Behavior negative table index!)?
  1. Why does cmd_inspect() check if (ferror(fp)) before comparing end_pos > pos_before?
  • *Hint 1:* What does fread() return when an underlying EIO read fault occurs mid-file (0, just like EOF!)?
  • *Hint 2:* If EIO stopped fread() at byte 24 of a 72-byte file, what would end_pos > pos_before misclassify the hardware I/O error as if ferror(fp) were not checked first?

13. Independent Challenges

  1. Near Transfer — Endian-Neutral Wire Codec (htole32 / Manual Shifts): Replace direct fwrite(&frame, 24, 1, out) struct dumps with explicit little-endian byte packing/unpacking (uint8_t wire[24]) so binary logs remain portable even across big-endian network processors.
  2. Far Transfer — Streaming Ring-Buffer Compactor: Extend telemetry_codec with a tail <in_bin> <last_k> subcommand that uses fseeko(fp, 0, SEEK_END) + ftello() to validate exact 24-byte alignment (end_pos % 24 == 0) and seeks directly to end_pos - last_k * 24 in $O(1)$ time without reading earlier megabytes!

14. Solutions & Explanations

  • Guided Question 1: Passing a negative signed char (other than EOF -1, and 0xFF collides with EOF!) to isalnum() or isdigit() invokes ISO C11 Undefined Behavior (indexing backward before glibc's __ctype_b_loc lookup table); always cast (unsigned char)c!
  • Guided Question 2: Both EOF and EIO cause fread(..., 1, fp) to return 0; checking ferror(fp) first reports an I/O error (exit 1) instead of falsely blaming the file for a PARTIAL_TAIL (exit 2).

Run locally in your terminal and check off each verification milestone.

Not started

Why Line Isolation Outperforms Stream fscanf()

Look at how fgets() + strtol() isolated every failure mode in fmt_safe_codec: when the 52-byte oversized_sensor_tag... line exceeded char line[48], line[len - 1] != '\n' detected the split line immediately, while ((ch = fgetc(fp)) != '\n' && ch != EOF) drained its tail cleanly, and subsequent lines parsed normally without stream corruption!

Guided Practice: Exact-Fit Dynamic String Allocation via snprintf(NULL, 0, ...)

Write a function char *format_alloc(const char *tag, uint64_t seq, ssize_t delta) that allocates an exact-sized heap string with zero truncation risk:

  1. Step 1 (Dry-run length query): Call int need = snprintf(NULL, 0U, "%s:%" PRIu64 ":%zd", tag, seq, delta); and return NULL if need < 0.
  2. Step 2 (Allocate need + 1 and format): Allocate size_t cap = (size_t)need + 1U; char *out = malloc(cap);, check out != NULL, run snprintf(out, cap, ...), and verify strlen(out) == (size_t)need.

Independent Practice: Strict Key-Value Config Parser (strtoul Hex & Octal)

Write a C11 parser kv_cfg_check.c (-std=c11 -Wall -Wextra -Werror) that reads "key = value # comment\n" lines via fgets(), strips # comments and whitespace, parses unsigned 32-bit integers supporting 0x hex, 0 octal, and base-10 via strtoul(val_s, &endp, 0) (rejecting leading '-' negative signs, which strtoul() surprisingly accepts modulo ULONG_MAX unless you check for '-' first!), and verifies val <= UINT32_MAX.

Common Production Pitfalls

warning: Symptom: Chaining pos += snprintf(buf + pos, sizeof(buf) - pos, ...) without checking each return value overflows buf on the next call after truncation! Root Cause: snprintf() returns the needed length (>= sizeof(buf) - pos), pushing pos past sizeof(buf) and wrapping unsigned sizeof(buf) - pos near SIZE_MAX. Fix: Validate if (ret < 0 || (size_t)ret >= sizeof(buf) - pos) before every pos += (size_t)ret.

warning: Symptom: Writing char key[32]; sscanf(line, "%32s", key); overwrites 1 byte past key[31] on 32-character inputs (ASan stack-buffer-overflow). Root Cause: scanf/sscanf field widths count payload characters excluding the mandatory terminating '\0' byte (32 + 1 = 33 bytes). Fix: Always set scanf string/scanset widths to sizeof(buf) - 1 (%31s or %31[^,\n] for char[32]).

Knowledge Check

quiz · 1 of 4

Given char buf[10]; int r = snprintf(buf, sizeof(buf), "sensor_%04d", 42);, what value is stored in r, and what condition proves output truncated?

quiz · 2 of 4

Which format string portably prints a size_t byte count followed by a uint64_t timestamp across both 32-bit ARMv7 and 64-bit x86-64 Linux builds under -Wall -Werror?

quiz · 3 of 4

(Review from earlier lesson) When fgets(line, sizeof(line), fp) returns NULL, how do you distinguish clean end-of-file from an underlying kernel read() fault?

quiz · 4 of 4

Why does production C11 text parsing prefer fgets() + strtol(num_s, &endp, 10) over fscanf(fp, "%d", &val) or atoi(num_s)?

Key takeaways

  • Never call sprintf(); bound every formatted write with snprintf(buf, sz, ...) (or dprintf(fd, ...)) and check ret < 0 || (size_t)ret >= sz before advancing buffer offsets.
  • Pair size_t/ssize_t with %zu/%zd and 64-bit fixed integers with <inttypes.h> PRId64/PRIu64 so -Wformat -Werror builds cleanly across 32-bit and 64-bit targets.
  • Cap scanf/sscanf string and scanset widths at sizeof(buf) - 1 (%31[^\n] for char[32]) to reserve 1 byte for '\0'.
  • Parse text line-first via fgets() (draining oversized lines) + strtol() (endp and ERANGE checks) so malformed records never wedge the stream.
  • With both kernel descriptors and Ring 3 stdio streams in your toolkit, Module 6 unites both layers to master kernel page-cache durability (fsync, fdatasync, O_DIRECT), two-stage fflush + fdatasync commits, and our capstone crash-safe CRC32 Write-Ahead Log!
Progress is saved on this device.
up next · module 5 labLab: Bounded stdio Sensor Log Parser & Binary Codec (45 min)
→ module 5 lab

search — fzf

0/0 ───────────────────────────────────────────

keyboard shortcuts — less

/
search
f
focus mode
[
previous
]
next
?
help
Esc
close

figure