From d53da19a79d68b1dc9abdb953c3d2e0497b33a7a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Niklas=20Hamb=C3=BCchen?= Date: Mon, 9 Sep 2024 16:43:25 +0200 Subject: [PATCH] slurp_battery_info: Fix reading uninitialised memory (#531) Fixes valgrind-found bug of the `for (walk = buf, ...` loop reading all of `buf` even though `buf` is null-terminated string (an only partly initialised char array). valgrind ./i3status -c ../etc/i3status.conf --run-once Conditional jump or move depends on uninitialised value(s) at 0x40F15A: slurp_battery_info (print_battery_info.c:164) by 0x40FA07: slurp_all_batteries (print_battery_info.c:558) by 0x40FCA6: print_battery_info (print_battery_info.c:612) by 0x409CA2: main (i3status.c:753) --- src/general.c | 3 ++- src/print_battery_info.c | 5 +++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/src/general.c b/src/general.c index 6036b695..5fbb668c 100644 --- a/src/general.c +++ b/src/general.c @@ -19,7 +19,8 @@ } /* - * Reads size bytes into the destination buffer from filename. + * Reads (size - 1) bytes into the destination buffer from filename, + * and null-terminate it. * * On success, true is returned. Otherwise, false is returned and the content * of destination is left untouched. diff --git a/src/print_battery_info.c b/src/print_battery_info.c index 096c3a90..1f567231 100644 --- a/src/print_battery_info.c +++ b/src/print_battery_info.c @@ -161,6 +161,11 @@ static bool slurp_battery_info(battery_info_ctx_t *ctx, struct battery_info *bat } for (walk = buf, last = buf; (walk - buf) < 1024; walk++) { + // `*walk` (slice of `buf`) is only initialised until `null` written by `slurp()` + if (*walk == '\0') { + break; + } + if (*walk == '\n') { last = walk + 1; continue;