Skip to content
Closed
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
src: don't include a null character in the WriteConsoleW call
Fixes: #7755
  • Loading branch information
seishun committed Aug 21, 2016
commit 5dc5e74a6fa8bc15dc67bfe878e9efe20073229e
2 changes: 1 addition & 1 deletion src/node.cc
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ static void PrintErrorString(const char* format, ...) {
vsprintf(out.data(), format, ap);

// Get required wide buffer size
n = MultiByteToWideChar(CP_UTF8, 0, out.data(), -1, nullptr, 0);
n = MultiByteToWideChar(CP_UTF8, 0, out.data(), n, nullptr, 0);
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think this works, it's going to fail when n == 0. (Also, passing n here but -1 three lines below doesn't look Obviously Correct to me.)

I think the patch should look something like this, using explicit sizes everywhere.

diff --git a/src/node.cc b/src/node.cc
index 3998659..1f0ba27 100644
--- a/src/node.cc
+++ b/src/node.cc
@@ -246,16 +246,19 @@ static void PrintErrorString(const char* format, ...) {
   }

   // Fill in any placeholders
-  int n = _vscprintf(format, ap);
-  std::vector<char> out(n + 1);
-  vsprintf(out.data(), format, ap);
+  const int numbytes = _vscprintf(format, ap);
+  if (numbytes <= 0) return;
+  std::vector<char> bytes(numbytes + 1);
+  vsprintf(bytes.data(), format, ap);

   // Get required wide buffer size
-  n = MultiByteToWideChar(CP_UTF8, 0, out.data(), -1, nullptr, 0);
-
-  std::vector<wchar_t> wbuf(n);
-  MultiByteToWideChar(CP_UTF8, 0, out.data(), -1, wbuf.data(), n);
-  WriteConsoleW(stderr_handle, wbuf.data(), n, nullptr, nullptr);
+  const int numchars =
+      MultiByteToWideChar(CP_UTF8, 0, bytes.data(), numbytes, nullptr, 0);
+  std::vector<wchar_t> chars(numchars);
+  MultiByteToWideChar(CP_UTF8, 0,
+                      bytes.data(), numbytes,
+                      chars.data(), numchars);
+  WriteConsoleW(stderr_handle, chars.data(), numchars, nullptr, nullptr);
 #else
   vfprintf(stderr, format, ap);
 #endif

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK, agreed, I'll make it simpler. (I wanted to avoid allocating for the unused wide null character, but it's not worth it if it makes the code more complicated)


std::vector<wchar_t> wbuf(n);
MultiByteToWideChar(CP_UTF8, 0, out.data(), -1, wbuf.data(), n);
Expand Down