16

I've tried convert a char* to wchar_t*, but I'm having some trouble using the mbstowcs and Visual Studio wants mbstowcs_s...

char *port; 
size_t size = strlen(port) + 1;  
wchar_t* portName = new wchar_t[size]; 
mbstowcs(portName, port, size);

How can I change the function to mbstowcs_s?

3
  • And what is the problem you're having? Have you checked the MSDN reference on mbstowcs_s? Commented Apr 24, 2015 at 12:04
  • 1
    What about disabling C4996 ?
    – willll
    Commented Apr 24, 2015 at 12:55
  • 1
    Your application security will benefit far more from std::string and std::wstring than from mbstowcs_s.
    – Ben Voigt
    Commented Apr 24, 2015 at 14:23

1 Answer 1

43

I wouldn't recommend disabling the secure code warnings when the fix to use the secure methods is so easy, so here you go:

    const char *port="8080";
    size_t size = strlen(port) + 1;  
    wchar_t* portName = new wchar_t[size]; 

    size_t outSize;
    mbstowcs_s(&outSize, portName, size, port, size-1);

    std::wcout << portName << std::endl;

Tested with cl /W3 /EHsc on VS2013.

2
  • 2
    Be carefull though to not create a memory leak! delete the portName Commented Nov 2, 2018 at 15:22
  • What exactly size and size-1 does in the API?
    – Arun
    Commented Mar 6, 2020 at 8:10

Not the answer you're looking for? Browse other questions tagged or ask your own question.