Converting std::wsting to char* with wcstombs_s

Justin R. picture Justin R. · Sep 5, 2013 · Viewed 14.1k times · Source

I have input strings that contain only digits (just the plain Latin ones, 0-9, so for example "0123"), stored as std::wstring, and I need each as a char*. What's the best way for me to do this? This is my initial approach:

void type::convertWStringToCharPtr(_In_ std::wstring input, _Out_ char * outputString)
{
    outputString = new char[outputSize];
    size_t charsConverted = 0;
    const wchar_t * inputW = input.c_str();
    wcstombs_s(&charsConverted, outputString, sizeof(outputString), inputW, input.length());
}

EDIT: The code below works. Thanks all!

void type::convertWStringToCharPtr(_In_ std::wstring input, _Out_ char * outputString)
{
    size_t outputSize = input.length() + 1; // +1 for null terminator
    outputString = new char[outputSize];
    size_t charsConverted = 0;
    const wchar_t * inputW = input.c_str();
    wcstombs_s(&charsConverted, outputString, outputSize, inputW, input.length());
}

Answer

Nemanja Boric picture Nemanja Boric · Sep 5, 2013

You are not allocating enough memory for your buffer:

char * outputString = new char[input.length()];

Should be

char * outputString = new char[input.length() + 1];

because of terminating NUL-character.

Oh, and also, as per pm100's comment: sizeof(outputString) is giving you the size of the pointer. You should use input.length() + 1, as that is the size of the buffer.