简体   繁体   中英

swprintf unexpected results

I am trying to use RtlStringCbPrintfW (safe version of swprintf), and got unexpected results when appending int to string. If i append the same string after int - all works. So my code:

WCHAR buffer[256];

    LPCWSTR pszFormat = L"%s %d";

    WCHAR* pszTxt = dataPath.Buffer;//*

    status = RtlStringCbPrintfW(buffer, sizeof(buffer), pszFormat, pszTxt, 1);
  • Here dataPath is UNICODE_STRING . So dataPath.Buffer is PWCH
    Here a see that buffer value is: buffer = wchar_t [168] "\\Device\\HarddiskVolume2\\foo\\Data??C???"

When watch buffer array i can see that '?' are:

0xcc00 '?'
0xcccc '?'

then after some bytes is actually target value 1 is located. The value of dataPath.Buffer:

   +0x048 DataPath         : _UNICODE_STRING "\Device\HarddiskVolume2\foo\Data"
      +0x000 Length           : 0x8c
      +0x002 MaximumLength    : 0x8c
      +0x008 Buffer           : 0xffffc000`01cd1d00  "\Device\HarddiskVolume2\foo\Data"

So what is the reson, null terminated char? Shouldn't be automaticly handled correctly with swprintf?

The documentation for UNICODE_STRING that you link to states that Buffer is not necessarily null-terminated and the %s format requires a null-terminated string.

You can restrict the length of a string printed with %s by specifying a precision:

WCHAR* pszTxt = dataPath.Buffer;
int Len = dataPath.Length;

RtlStringCbPrintfW(buffer, sizeof(buffer), L"%.*s %d", Len, pszTxt, 1);
%wZ 

类型字段字符应用于UNICODE_STRING结构。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM