From 18d62312329cc927ef73bd842c33b5606c360f11 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kacper=20S=C5=82omi=C5=84ski?= Date: Mon, 18 Mar 2024 00:14:39 +0100 Subject: [PATCH] printf: Fix string precision handling Previously we were assuming that the input string is always null-terminated, which could lead to an out-of-bounds access if that wasn't the case. --- include/frg/printf.hpp | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/include/frg/printf.hpp b/include/frg/printf.hpp index b7e9a87..a10a94e 100644 --- a/include/frg/printf.hpp +++ b/include/frg/printf.hpp @@ -250,9 +250,11 @@ void do_printf_chars(S &sink, char t, format_options opts, if(!s) s = "(null)"; - int length = string_view{s}.size(); - if(opts.precision && *opts.precision < length) - length = *opts.precision; + int length; + if(opts.precision) + length = generic_strnlen(s, *opts.precision); + else + length = generic_strlen(s); if(opts.left_justify) { for(int i = 0; i < length && s[i]; i++) @@ -271,9 +273,11 @@ void do_printf_chars(S &sink, char t, format_options opts, if(!s) s = L"(null)"; - int length = basic_string_view{s}.size(); - if(opts.precision && *opts.precision < length) - length = *opts.precision; + int length; + if(opts.precision) + length = generic_strnlen(s, *opts.precision); + else + length = generic_strlen(s); if(opts.left_justify) { for(int i = 0; i < length && s[i]; i++)