Question

hi im loking for some advice im working in a command interpreter for class and i have this "command" (that is a class) that get some c strings from internal variables and make an std::wstring, then i cast it to wchar_t * but when i return it i get just garbage on the variable,p.e

content of variable before return:

comandos disponibles: ayuda salir

content of variable after return:

����������������������������������������

i tried to make the function return an const wchar_t * but it also dont work, but if i put a string in the return it just work fine pe.

return L"test"

any idea?

--edit--

this is the code i´m using

wchar_t * ayuda::run(std::list<char* const> * lista){

    std::wstring out;

    out += L"comandos disponibles:\n"; //static header
    commandMap map = loadMap();//get a map whit all the function names

    commandMap::iterator it;
    for(it = map.begin(); it != map.end();it++){
        out+=std::wstring(it->first.begin(),it->first.end())+L"\n";// append the command name to the string
    }
    wchar_t * _out = const_cast<wchar_t*>( out.c_str() ); //cast to wchar *
    return _out;
}
Was it helpful?

Solution

Are you trying to return a wchar_t * allocated on the stack ?

wchar_t *MyFunction()
{
    wchar_t myString[] = L"This will be destroyed from the stack on returned";
    return myString;
}

In that case, the string is removed from the stack, and then garbage is returned. Which would explain what you see.

In C++, use std::string or std::wstring for strings, it prevents memory leaks and also provides useful functions. Avoid arrays as much as you can.

#include <string>

std::wstring MyFunction()
{
    std::wstring myString = L"This will be copied, since this is not a pointer, but an instance of an object.";
    return myString;
}

The other way would be to allocate the string on the heap, be then you would need to ensure to delete it somewhere otherwise there will be a memory leak.

wchar_t *MyFunction()
{
    wchar_t myString[] = L"This will be destroyed from the stack on returned";
    size_t myStringLen = wcslen(myString);

    wchar_t *outString = new wchar_t[myStringLen+1]; //allocate heap memory
    wcscpy(outString, myString); //copy the string to heap memory

    return outString; //return a string that will not be destroyed.
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top