简体   繁体   中英

Why I get wrong char array when I use WideCharToMultiByte?

Windows 7, Visual Studio 2015.

#ifdef UNICODE
    char *buffer = NULL;
    int iBuffSize = WideCharToMultiByte(CP_ACP, 0, result_msg.c_str(),
        result_msg.size(), buffer, 0, NULL, NULL);

    buffer = static_cast<char*>(malloc(iBuffSize));
    ZeroMemory(buffer, iBuffSize);

    WideCharToMultiByte(CP_ACP, 0, result_msg.c_str(),
        result_msg.size(), buffer, iBuffSize, NULL, NULL);

    string result_msg2(buffer);
    free(buffer);

    throw runtime_error(result_msg2);
#else
    throw runtime_error(result_msg);
#endif  

result_msg is std::wstring for unicode, and std::string for the multi-byte character set.

For Multi-byte character set:

在此处输入图片说明

For Unicode character set:

在此处输入图片说明

You specified the input string size as result_msg.size() , which does not include the terminating null character, and so the output won't be null-terminated, either. But when you convert buffer to a string , you are not specifying the size of buffer , so the string constructor expects a null terminator. Without that terminator, it is grabbing data from surrounding memory until it encounters a null byte (or get a memory access error).

Either use result_msg.size() + 1 for the input size, or specify -1 as the input size to let WideCharToMultiByte() determine the input size automatic. Either approach will include a null terminator in the output.

Or, keep using result_msg.size() s the input size, and use the value of iBuffSize when converting buffer to a string , then you don't need a null terminator:

string result_msg2(buffer, iBuffSize);

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