Skip to content

Commit aabec3c

Browse files
chris0x44BillyONeal
authored andcommitted
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.
1 parent b0b2fc4 commit aabec3c

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

Release/src/utilities/asyncrt_utils.cpp

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -265,8 +265,7 @@ std::string windows_category_impl::message(int errorCode) const CPPREST_NOEXCEPT
265265
}
266266
#endif
267267

268-
std::wstring buffer;
269-
buffer.resize(buffer_size);
268+
std::wstring buffer(buffer_size, 0);
270269

271270
const auto result = ::FormatMessageW(
272271
dwFlags,
@@ -277,11 +276,15 @@ std::string windows_category_impl::message(int errorCode) const CPPREST_NOEXCEPT
277276
buffer_size,
278277
NULL);
279278

279+
280280
if (result == 0)
281281
{
282282
return "Unable to get an error message for error code: " + std::to_string(errorCode) + ".";
283283
}
284284

285+
// strip exceeding characters of the initial resize call
286+
buffer.resize(result);
287+
285288
return utility::conversions::to_utf8string(buffer);
286289
}
287290

Release/tests/functional/utils/strings.cpp

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -373,6 +373,17 @@ TEST(scan_string_locale, "Ignore:Android", "Locale unsupported on Android")
373373
}
374374
}
375375

376+
377+
#ifdef _WIN32
378+
TEST(windows_category_message)
379+
{
380+
// Ensure the error message string returned by windows_category doesn't contain trailing zeros.
381+
std::string error_message = utility::details::windows_category().message( 0 );
382+
std::string zero_terminated_copy = error_message.c_str();
383+
VERIFY_ARE_EQUAL( zero_terminated_copy, error_message );
384+
}
385+
#endif // _WIN32
386+
376387
}
377388

378389
}}} //namespaces

0 commit comments

Comments
 (0)