From aabec3cbca699f238e9b78226c834b9789fdbbb6 Mon Sep 17 00:00:00 2001 From: Christian <43907599+chris0x44@users.noreply.github.com> Date: Sun, 11 Nov 2018 01:35:07 +0100 Subject: [PATCH] Fix string size for error message generated by windows_category (#966) Due to the initial allocation of the error message, the returned std::string had a size of 4096. Since FormatMessageW already returns the number of characters written to the buffer an additional call to resize using the returned count will neatly trim the string. --- Release/src/utilities/asyncrt_utils.cpp | 7 +++++-- Release/tests/functional/utils/strings.cpp | 11 +++++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/Release/src/utilities/asyncrt_utils.cpp b/Release/src/utilities/asyncrt_utils.cpp index 9f9e7f852f..0bafacd514 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 19d1b43cfd..8f6957f61a 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