diff --git a/include/fmt/format-inl.h b/include/fmt/format-inl.h index b7f89e8d..4383c924 100644 --- a/include/fmt/format-inl.h +++ b/include/fmt/format-inl.h @@ -14,6 +14,7 @@ # include # include # include +# include // std::bad_alloc #endif #if defined(_WIN32) && !defined(FMT_USE_WRITE_CONSOLE) @@ -78,11 +79,16 @@ template auto locale_ref::get() const -> Locale { namespace detail { +FMT_FUNC auto allocate(size_t size) -> void* { + void* p = malloc(size); + if (!p) FMT_THROW(std::bad_alloc()); + return p; +} + FMT_FUNC void format_error_code(detail::buffer& out, int error_code, string_view message) noexcept { - // Report error code making sure that the output fits into - // inline_buffer_size to avoid dynamic memory allocation and potential - // bad_alloc. + // Report error code making sure that the output fits into inline_buffer_size + // to avoid dynamic memory allocation and potential bad_alloc. out.try_resize(0); static const char SEP[] = ": "; static const char ERROR_STR[] = "error "; diff --git a/include/fmt/format.h b/include/fmt/format.h index 8c143cfe..9b02b595 100644 --- a/include/fmt/format.h +++ b/include/fmt/format.h @@ -54,7 +54,6 @@ # include // std::byte # include // uint32_t # include // std::numeric_limits -# include // std::bad_alloc # if defined(__GLIBCXX__) && !defined(_GLIBCXX_USE_DUAL_ABI) // Workaround for pre gcc 5 libstdc++. # include // std::allocator_traits @@ -736,6 +735,8 @@ using fast_float_t = conditional_t; template using is_double_double = bool_constant::digits == 106>; +FMT_API auto allocate(size_t size) -> void*; + // An allocator that uses malloc/free to allow removing dependency on the C++ // standard library runtime. std::decay is used for back_inserter to be found by // ADL when applied to memory_buffer. @@ -744,9 +745,7 @@ template struct allocator : private std::decay { auto allocate(size_t n) -> T* { FMT_ASSERT(n <= max_value() / sizeof(T), ""); - T* p = static_cast(malloc(n * sizeof(T))); - if (!p) FMT_THROW(std::bad_alloc()); - return p; + return static_cast(detail::allocate(n * sizeof(T))); } void deallocate(T* p, size_t) { free(p); }