Skip to content

Commit

Permalink
Fix handling of null strings with the s specifier
Browse files Browse the repository at this point in the history
  • Loading branch information
vitaut committed Nov 16, 2023
1 parent 45e124e commit 649fe0f
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 4 deletions.
7 changes: 4 additions & 3 deletions include/fmt/format.h
Original file line number Diff line number Diff line change
Expand Up @@ -2342,9 +2342,10 @@ template <typename Char, typename OutputIt>
FMT_CONSTEXPR auto write(OutputIt out, const Char* s,
const format_specs<Char>& specs, locale_ref)
-> OutputIt {
return specs.type != presentation_type::pointer
? write(out, basic_string_view<Char>(s), specs, {})
: write_ptr<Char>(out, bit_cast<uintptr_t>(s), &specs);
if (specs.type == presentation_type::pointer)
return write_ptr<Char>(out, bit_cast<uintptr_t>(s), &specs);
if (!s) throw_format_error("string pointer is null");
return write(out, basic_string_view<Char>(s), specs, {});
}

template <typename Char, typename OutputIt, typename T,
Expand Down
6 changes: 5 additions & 1 deletion test/format-test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1531,8 +1531,12 @@ TEST(format_test, format_cstring) {
EXPECT_EQ("test", fmt::format("{0:s}", "test"));
char nonconst[] = "nonconst";
EXPECT_EQ("nonconst", fmt::format("{0}", nonconst));
auto nullstr = static_cast<const char*>(nullptr);
EXPECT_THROW_MSG(
(void)fmt::format(runtime("{0}"), static_cast<const char*>(nullptr)),
(void)fmt::format("{}", nullstr),
format_error, "string pointer is null");
EXPECT_THROW_MSG(
(void)fmt::format("{:s}", nullstr),
format_error, "string pointer is null");
}

Expand Down

0 comments on commit 649fe0f

Please sign in to comment.