开发者

Allocating StringCchVPrintfW string format buffer in C++?

开发者 https://www.devze.com 2023-03-17 13:56 出处:网络
I found this code in a Microsoft Windows SDK example: wstring buffer; void formatfunction(format, ...) {

I found this code in a Microsoft Windows SDK example:

wstring buffer;
void formatfunction(format, ...) {
    VPRINTF_VAR_PARAMS(buffer, format);
    do_something_with(buffer);
}

#define VPRINTF_VAR_PARAMS(buffer, format)          \
{                                                   \
    buffer.resize(MAX_VPRINTF_BUFFER_SIZE, L'\0');  \
    va_list marker;                                 \
    va_start( marker, format );                     \
    HRESULT hr = StringCchVPrintfW(                 \
        WString2Buffer(buffer),                     \
        buffer.length(),                            \
        format.c_str(),                             \
        marker );                                   \
    if (FAILED(hr)                                  \
        && (hr != STRSAFE_E_INSUFFICIENT_BUFFER))   \
        throw(hr);                                  \
    va_end( marker );                               \
}

where MAX_VPRINTF_BUFFER_SIZE is a large constant (4096). Now:

Isn't the wstring actually enc开发者_开发百科oded in UTF-16 and therefore a variable length format (using more than two bytes for certain foreign characters)?

If, however, the buffer is resized to 4096 * 2 bytes, while StringCchVPrintfW counts in characters, not bytes, it might lead to a buffer overflow if a character wider than 2 bytes is encountered.

Is my assumption correct? How could this problem be addressed?

0

精彩评论

暂无评论...
验证码 换一张
取 消