简体   繁体   中英

Converting char to wide char

I am trying to converts a sequence of multibyte characters to a corresponding sequence of wide characters using the mbstowcs_s function. But I keep having the following heap corruption problem. Can anyone tell me how to fix that?

在此处输入图片说明

Here is a sample code. When debugging, it is always the line delete wc_name causing the problem. I know it shouldn't be it.

#include <Windows.h>
#include <iostream>
#include <string>
int main (int argc, char *argv[]) { 
    size_t returnValue; // The number of characters converted.
    const size_t sizeInWords = 50; // The size of the wcstr buffer in words
    const char* c_name = "nanana"; // The address of a sequence of characters
    wchar_t *wc_name = new wchar_t(50); 

    errno_t err = mbstowcs_s(&returnValue, wc_name, sizeInWords, 
                                              c_name, strlen(c_name) );

    wcout << wc_name << endl;
    delete wc_name;
    return 0;
}

wchar_t *wc_name = new wchar_t(50); should be wchar_t *wc_name = new wchar_t[50]; to allocate an array. And corresponding delete wc_name should be delete[] wc_name; . BTW, if you know the size of the array at compile time itself, there is no need for dynamic memory allocation. You can simply do wchar_t wc_name[50]; .

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