Skip to content

Commit

Permalink
Fix string size for error message generated by windows_category (#966)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
chris0x44 authored and BillyONeal committed Nov 11, 2018
1 parent b0b2fc4 commit aabec3c
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
7 changes: 5 additions & 2 deletions Release/src/utilities/asyncrt_utils.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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);
}

Expand Down
11 changes: 11 additions & 0 deletions Release/tests/functional/utils/strings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit aabec3c

Please sign in to comment.