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.
This commit is contained in:
Christian 2018-11-11 01:35:07 +01:00 коммит произвёл Billy O'Neal
Родитель b0b2fc4a0a
Коммит aabec3cbca
2 изменённых файлов: 16 добавлений и 2 удалений

Просмотреть файл

@ -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);
}

Просмотреть файл

@ -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