From d589ac1cbfa4e0f2225ab37c9f9c5fd3b5ea1b0e Mon Sep 17 00:00:00 2001 From: Andrew Schwartzmeyer Date: Wed, 22 Jul 2015 16:36:19 -0700 Subject: [PATCH] Refactor setting of lpnSize when buffer size is insufficient --- src/impl/getusername.cpp | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/impl/getusername.cpp b/src/impl/getusername.cpp index 282cd930d..2e1e1dd12 100644 --- a/src/impl/getusername.cpp +++ b/src/impl/getusername.cpp @@ -85,9 +85,15 @@ BOOL GetUserName(WCHAR_T *lpBuffer, LPDWORD lpnSize) std::vector output; SCXCoreLib::Utf8ToUtf16le(username, output); - if (output.size()/2 + 1 > *lpnSize) { + // The length is the number of characters in the string, which + // is half the string size because UTF-16 encodes two bytes + // per character, plus one for the trailing null. + const DWORD length = output.size()/2 + 1; + if (length > *lpnSize) { errno = ERROR_INSUFFICIENT_BUFFER; - *lpnSize = output.size()/2 + 1; + // Set lpnSize if buffer is too small to inform user + // of necessary size + *lpnSize = length; return 0; }