Does MultiByteToWideChar() result includes the terminating null character?

thebluetropics 1,046 Reputation points
2022-11-19T00:58:29.62+00:00

I have used MultiByteToWideChar() multiple times. I just assume the function add character \0 at the end of the result wide string, and it works all of the time.
I just found it didn't work this time, the string does have \0 at the end, which makes my string longer than expected (displaying weird chinese characters). In other words, does MultiByteToWideChar() also includes the terminating zero character at the end of the result wide string?

I don't find the documentation mentions about this, or am I just missing something?

Windows development | Windows API - Win32
Developer technologies | C++
0 comments No comments
{count} votes

Accepted answer
  1. RLWA32 49,551 Reputation points
    2022-11-19T01:29:35.03+00:00

    The function includes a null terminator in the result depending on how it is called. From nf-stringapiset-multibytetowidechar -
    "[in] cbMultiByte

    Size, in bytes, of the string indicated by the lpMultiByteStr parameter. Alternatively, this parameter can be set to -1 if the string is null-terminated. Note that, if cbMultiByte is 0, the function fails.

    If this parameter is -1, the function processes the entire input string, including the terminating null character. Therefore, the resulting Unicode string has a terminating null character, and the length returned by the function includes this character.

    If this parameter is set to a positive integer, the function processes exactly the specified number of bytes. If the provided size does not include a terminating null character, the resulting Unicode string is not null-terminated, and the returned length does not include this character."

    Also, "MultiByteToWideChar does not null-terminate an output string if the input string length is explicitly specified without a terminating null character. To null-terminate an output string for this function, the application should pass in -1 or explicitly count the terminating null character for the input string."

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.