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;
}
Are you trying to return a wchar_t * allocated on the stack ?
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.
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.