C++, conversion from utility:string_t to std::string crashes on return

XTT picture XTT · Jan 21, 2016 · Viewed 9.8k times · Source

I am using casablanca library to serialize json values.

I tried making a conversion to std::string using typedef std::wstring string_t and this to convert from wstring to string. It's compiling fine but the program just crashes when executing the return line.

std::string getString()
{
    web::json::value cvalue;
    /* ----- code ----- */
    typedef std::wstring string_t;
    string_t outputString = cvalue.serialize();

    typedef std::codecvt_utf8<wchar_t> convert_type;
    std::wstring_convert<convert_type, wchar_t> converter;
    std::string converted_str = converter.to_bytes(outputString);

    return converted_str;
}

I can't understand why this is crashing. Below is the line calling that function.

std::string s = getString();

The program triggered a break point here at line free(_Ptr) in a file called xdebug. I don't really understand what it's saying here. Hope this helps clarify things for you.

template<class _Ty>
    void __CLRCALL_OR_CDECL _DebugHeapDelete(_Ty *_Ptr)
    {   // delete from the debug CRT heap even if operator delete exists
    if (_Ptr != 0)
        {   // worth deleting
        _Ptr->~_Ty();
        // delete as _NORMAL_BLOCK, not _CRT_BLOCK, since we might have
        // facets allocated by normal new.
        free(_Ptr);
        }
    }

Thanks!

Answer

roschuma picture roschuma · Feb 2, 2016

In the C++ REST SDK there is a function to convert utility::string_t into a utf8 std::string: utility::conversions::to_utf8string

reference documentation