diff --git a/Release/src/utilities/asyncrt_utils.cpp b/Release/src/utilities/asyncrt_utils.cpp index 9f9e7f852..0bafacd51 100644 --- a/Release/src/utilities/asyncrt_utils.cpp +++ b/Release/src/utilities/asyncrt_utils.cpp @@ -265,8 +265,7 @@ std::string windows_category_impl::message(int errorCode) const CPPREST_NOEXCEPT } #endif - std::wstring buffer; - buffer.resize(buffer_size); + std::wstring buffer(buffer_size, 0); const auto result = ::FormatMessageW( dwFlags, @@ -277,11 +276,15 @@ std::string windows_category_impl::message(int errorCode) const CPPREST_NOEXCEPT buffer_size, NULL); + if (result == 0) { return "Unable to get an error message for error code: " + std::to_string(errorCode) + "."; } + // strip exceeding characters of the initial resize call + buffer.resize(result); + return utility::conversions::to_utf8string(buffer); } diff --git a/Release/tests/functional/utils/strings.cpp b/Release/tests/functional/utils/strings.cpp index 19d1b43cf..8f6957f61 100644 --- a/Release/tests/functional/utils/strings.cpp +++ b/Release/tests/functional/utils/strings.cpp @@ -373,6 +373,17 @@ TEST(scan_string_locale, "Ignore:Android", "Locale unsupported on Android") } } + +#ifdef _WIN32 +TEST(windows_category_message) +{ + // Ensure the error message string returned by windows_category doesn't contain trailing zeros. + std::string error_message = utility::details::windows_category().message( 0 ); + std::string zero_terminated_copy = error_message.c_str(); + VERIFY_ARE_EQUAL( zero_terminated_copy, error_message ); +} +#endif // _WIN32 + } }}} //namespaces