I have this simple function:
const wchar_t *StringManager::GetWCharTStar(int stringId)
{
std::wstring originalString = StringManager::GetString(stringId);
const wchar_t *retStr = originalString.c_str();
return retStr;
}
At the second line of that function, I have the correct wchar_t*. However, when I go to return, the data switches to garbage data. There are no functions in between. What gives?!
originalString is allocated on the stack. The .c_str() method just returns a pointer to some contiguous internal memory of the wstring object. When the function returns, originalString goes out of scope and is destroyed, therefore the pointer value you return points to deleted memory.
If you need to do this, you should make a copy of the data into memory you allocate with new or malloc(), and then the caller must delete/free() that memory.