fix null pointer arithmetic for %s with precision in vprintf

This commit is contained in:
Aizal Khan 2026-10-27 13:43:57 +05:30
parent f87a75e152
commit 3056412223
2 changed files with 10 additions and 5 deletions

View File

@ -494,11 +494,13 @@ void vprintf(buffer<Char>& buf, basic_string_view<Char> format,
}
if (specs.precision >= 0 && arg.type() == type::cstring_type) {
auto str = arg.visit(get_cstring<Char>());
auto str_end = str + specs.precision;
auto nul = std::find(str, str_end, Char());
auto sv = basic_string_view<Char>(
str, to_unsigned(nul != str_end ? nul - str : specs.precision));
arg = sv;
if (str) {
auto str_end = str + specs.precision;
auto nul = std::find(str, str_end, Char());
auto sv = basic_string_view<Char>(
str, to_unsigned(nul != str_end ? nul - str : specs.precision));
arg = sv;
}
}
if (specs.fill_unit<Char>() == '0') {
if (is_arithmetic_type(arg.type()) && specs.align() != align::left) {

View File

@ -544,6 +544,9 @@ TEST(printf_test, string) {
const char* null_str = nullptr;
EXPECT_PRINTF("(null)", "%s", null_str);
EXPECT_PRINTF(" (null)", "%10s", null_str);
// A precision must not apply pointer arithmetic to a null string argument.
EXPECT_PRINTF("(null)", "%.3s", null_str);
EXPECT_PRINTF("(null)", "%.0s", null_str);
}
TEST(printf_test, pointer) {