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.
What you'll learn
- Format fixed-width and pointer-sized integers portably (
%zu,PRId64,PRIu64) viasnprintf()with-Wformatclean. - Detect formatted output truncation deterministically by checking
ret < 0 || (size_t)ret >= sizeon everysnprintf(). - Construct fault-isolated text parsers combining line-bounded
fgets(), width-capped scansets, andERANGEstrtol().
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 Tool | Exact C11 / POSIX Idiom | Safety & 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 formatting | Emits 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] + strtol | Width = sizeof(dst) - 1; check ERANGE & *endp == '\0' | Prevents buffer overflow and rejects "12abc" or LONG_MAX overflow |
Figure 5.3. Truncation-checked snprintf() accumulator math, <inttypes.h> specifiers, and fault-isolated fgets() + strtol() parsing.
- Step 1. Frame bounded lines with fgets(line, sizeof(line), fp) and check ferror(fp) vs feof(fp) on NULL exit.
- Step 2. When line[len - 1] != '\\n' before EOF, drain excess bytes up to '\\n' via int fgetc(fp) to quarantine oversized lines.
- Step 3. Split key=value fields with width sizeof(dst) - 1 (%15[^=] for char[16]) so '\\0' never overflows.
- 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$ 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; }- Guard ret < 0 || (size_t)ret >= rem BEFORE advancing *pos so a truncated snprintf() never wraps cap - *pos.
- Drain remaining characters up to '\n' when an oversized line lacks a newline so its tail cannot masquerade as the next record.
- 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-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→ open standalone lab workbench
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
- Ingest untrusted CSV sensor streams via bounded
fgets()(draining> 127-byte oversized lines up to'\n') and validate<id>,<seq>,<mv>fields withstrtoul()/strtol()(ERANGEand character-set guards). - Serialize
24-bytestruct sensor_framebatches (16records perfwrite()call) onto"wbe"streams with checkedferror()andfclose(). - Inspect binary streams via
while (fread(&frame, sizeof(frame), 1, fp) == 1)(neverwhile (!feof(fp))), detecting partial trailing bytes (exit 2) viaftello()/fseeko(). - Enforce
snprintf(buf, cap, ...)bounds by detectingneeded < 0 || (size_t)needed >= cap(exit 3).
3. Environment Requirements
- Host Execution Environment (Tested): Linux
6.12LTS (x86_64,glibc2.39+),#define _POSIX_C_SOURCE 200809Land#define _FILE_OFFSET_BITS 64. - Target Board Portability (
ARMv7Cortex-A7):struct sensor_frame(char id[16]; uint32_t seq; int32_t mv;) has natural4-byte alignment and0padding bytes (sizeof == 24) across both 32-bitARMv7and 64-bitx86_64little-endian targets, andint ch = fgetc(in)avoids the unsigned-charARMv7infinite 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$ 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)
- Wedging
fscanf()(encode):while (fscanf(in, "%15[^,],%u,%d\n", ...) == 3)halts at the very first malformed or#comment line (valid=0or partial output) and silently wraps overflowing integers! - Off-by-one
while (!feof(fp))(inspect): Runs an extra loop iteration atEOF, countingVALID=4on a3-record file! - Missing torn-tail &
snprintf()checks: Ignores partial trailing bytes (PARTIAL_TAIL) and prints silently truncated strings with exit0.
Warning-Clean Reference (files/telemetry_codec.c)
- Oversized-Line Drain (
cmd_encode): Checksif (len > 0 && line[len - 1] != '\n' && !feof(in))and drains viaint ch; while ((ch = fgetc(in)) != '\n' && ch != EOF) {}before incrementingrejected, keeping the next line cleanly aligned! - Strict Token Validation (
parse_csv_line): Rejects leading'-'beforestrtoul()(becausestrtoul("-1", ...)legally wraps moduloULONG_MAX!), checkserrno == 0 && *end_seq == ',' && seq_ul <= UINT32_MAX, and checksmv_lin[-100000, 100000]. - Torn-Tail & Truncation Guards (
cmd_inspect): Snapshotspos_before = ftello(fp)prior to eachfread(&frame, 24, 1, fp), comparesSEEK_ENDend_pos > pos_before(exit 2), and checksneeded < 0 || (size_t)needed >= cap(exit 3).
7. Expected Output
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/58. 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
strtoul("-5")Sign-Wrap Experiment: Comment outif (!isdigit((unsigned char)*s_seq)) return -1;in a scratch copy and passvcore,-1,3300on 64-bit Linux to observestrtoul()parse-1as18446744073709551615UL(> UINT32_MAX), and passvcore,-1,3300on 32-bitILP32whereULONG_MAX == UINT32_MAX(4294967295accepted silently without theisdigitguard!).straceBatching Verification: Encode1,000CSV rows (24,000bytes) understrace -e trace=read,writeand confirmglibc's8 KiB_IOFBFbuffer reduces1,000logical records to3write()syscalls!- In-Memory Fuzzing via
fmemopen: Refactorcmd_encodeintoencode_streams(FILE *in, FILE *out)and fuzzparse_csv_linein memory usingfmemopen()+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):
| Metric | Measured 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
| Symptom | Root Cause | Fix |
|---|---|---|
VALID is N + 1 on every clean binary file | Used while (!feof(fp)) instead of checking fread() == 1 | Loop on while (fread(&frame, sizeof(frame), 1, fp) == 1) |
Infinite loop on ARMv7 when draining > 128B CSV line | Stored fgetc(in) in char ch (unsigned char 255 != -1 EOF) | Declare int ch; for fgetc(in) |
Negative sequence -1 accepted on 32-bit targets | strtoul() allows leading '-' and negates modulo ULONG_MAX | Check isdigit((unsigned char)*s_seq) before strtoul() |
-Wsign-compare or -Wformat error on size_t | Printed size_t with %lu instead of %zu | Use %zu for size_t across 32/64-bit builds |
12. Guided Questions
- Why must
valid_id_char((unsigned char)line[i])castchartounsigned charbefore calling<ctype.h>isalnum()?
- *Hint 1:* Check
man 3 isalnumfor the exact input domain required by ISO C11<ctype.h>functions (unsigned charwidened toint, orEOF). - *Hint 2:* On x86-64 (signed
char), what negativeintvalue is passed toisalnum()if an untrusted UTF-8 byte0xC3arrives without the(unsigned char)cast (Undefined Behaviornegative table index!)?
- Why does
cmd_inspect()checkif (ferror(fp))before comparingend_pos > pos_before?
- *Hint 1:* What does
fread()return when an underlyingEIOread fault occurs mid-file (0, just likeEOF!)? - *Hint 2:* If
EIOstoppedfread()at byte24of a72-byte file, what wouldend_pos > pos_beforemisclassify the hardware I/O error as ifferror(fp)were not checked first?
13. Independent Challenges
- Near Transfer — Endian-Neutral Wire Codec (
htole32/ Manual Shifts): Replace directfwrite(&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. - Far Transfer — Streaming Ring-Buffer Compactor: Extend
telemetry_codecwith atail <in_bin> <last_k>subcommand that usesfseeko(fp, 0, SEEK_END)+ftello()to validate exact24-byte alignment (end_pos % 24 == 0) and seeks directly toend_pos - last_k * 24in $O(1)$ time without reading earlier megabytes!
14. Solutions & Explanations
- Guided Question 1: Passing a negative
signed char(other thanEOF-1, and0xFFcollides withEOF!) toisalnum()orisdigit()invokes ISO C11 Undefined Behavior (indexing backward beforeglibc's__ctype_b_loclookup table); always cast(unsigned char)c! - Guided Question 2: Both
EOFandEIOcausefread(..., 1, fp)to return0; checkingferror(fp)first reports an I/O error (exit 1) instead of falsely blaming the file for aPARTIAL_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:
- Step 1 (Dry-run length query): Call
int need = snprintf(NULL, 0U, "%s:%" PRIu64 ":%zd", tag, seq, delta);and returnNULLifneed < 0. - Step 2 (Allocate
need + 1and format): Allocatesize_t cap = (size_t)need + 1U; char *out = malloc(cap);, checkout != NULL, runsnprintf(out, cap, ...), and verifystrlen(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
Key takeaways
- Never call
sprintf(); bound every formatted write withsnprintf(buf, sz, ...)(ordprintf(fd, ...)) and checkret < 0 || (size_t)ret >= szbefore advancing buffer offsets. - Pair
size_t/ssize_twith%zu/%zdand 64-bit fixed integers with<inttypes.h>PRId64/PRIu64so-Wformat -Werrorbuilds cleanly across 32-bit and 64-bit targets. - Cap
scanf/sscanfstring and scanset widths atsizeof(buf) - 1(%31[^\n]forchar[32]) to reserve1byte for'\0'. - Parse text line-first via
fgets()(draining oversized lines) +strtol()(endpandERANGEchecks) so malformed records never wedge the stream. - With both kernel descriptors and
Ring 3stdiostreams in your toolkit, Module 6 unites both layers to master kernel page-cache durability (fsync,fdatasync,O_DIRECT), two-stagefflush+fdatasynccommits, and our capstone crash-safeCRC32Write-Ahead Log!