-1

I see that a lot of functions need you to set a size for the string which is the output.

GetComputerNameW needs:

WCHAR wStrName[16U];
DWORD uSize = 16U;
GetComputerNameW(wStrName, &uSize);

RegSetValueExW needs:

WCHAR wStrExec[1024U];
RegSetValueExW(..., (wcslen(wStrExec) + 1U) * sizeof(WCHAR));

GetWindowTextW needs:

WCHAR wStrText[1024U];
GetWindowsTextW(..., sizeof(wStrText));

GetModuleBaseNameW needs:

WCHAR wStrName[1024U];
GetModuleBaseNameW(..., sizeof(wStrName) / sizeof(WCHAR));

My question is, how to make the difference between the sizes set? The strings are always defined as WCHAR and the sizes set differ so much.

  • 2
    In short, you need to read the documentation of each individual function, determine exactly what needs to be passed, then pass that. Note that `sizeof(wStrName) / sizeof(WCHAR)` can be shortened to `_countof(wStrName)`, using `_countof` from the Visual C++ `` (`_countof` is a nonstandard extension). – James McNellis Jan 14 '14 at 20:15
  • Could you rephrase your question please? I don't understand what you're asking. Are you asking why we need to pass size information, or how these functions make use of the size information, or something else? – Praetorian Jan 14 '14 at 20:16
  • Your `GetWindowTextW` is incorrect. It should be 1024 or `sizeof(wStrText) / sizeof(WCHAR)`. – Raymond Chen Jan 14 '14 at 20:24

1 Answers1

0

If you carefully read the documentation, you'll see that the size parameter is the size of the output buffer in bytes typically:

cbData [in]

The size of the information pointed to by the lpData parameter, in bytes. If the data is of type REG_SZ, REG_EXPAND_SZ, or REG_MULTI_SZ, cbData must include the size of the terminating null character or characters.

Which of course yields that you need to:

WCHAR wStrExec[1024U];
RegSetValueExW(..., sizeof (wStrExec));
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
John Dibling
  • 99,718
  • 31
  • 186
  • 324
  • In the case of `RegSetValueExW` with a string, you should only use the part of the buffer that contains data. Otherwise you're writing uninitialized stack garbage into the registry which could be an information disclosure security vulnerability. – Raymond Chen Jan 14 '14 at 20:23
  • @RaymondChen: Fair enough. – John Dibling Jan 14 '14 at 20:24