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?

enter image description here

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];.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top