core::stringw Text is created on the stack. The memory that it allocates internally is on the heap, but when func() returns, Text is destroyed, its destructor is called, and its memory freed. You are returning a pointer to freed memory, which is being crapped over before you get a chance to copy the contents.
Code: Select all
const wchar_t* func()
{
core::stringw Text(L"First line\nSecond line\nThird line");
// Text now contains that string in memory allocated on the heap.
return Text.c_str();
// The function will now return a pointer to that heap memory
} // UH OH - Text is destroyed, and its destructor deletes the heap memory. That makes it fair game to be re-used.
// The pointer to the destroyed memory is returned...
int main()
{
// ...and here's func(), returning that pointer to the destroyed memory.
// The contents of that memory could be anything. You're seeing a couple of characters being crapped over
// but the entire memory could be gibberish by the time it gets passed into the constructor of text()
core::stringc text(func());
std::cout << text.c_str() << std::endl;
}
I'm not sure what your requirements are, but I'd recommend returning a stringw, either by value or reference.
E.g.
Code: Select all
core::stringw func()
{
core::stringw Text(L"First line\nSecond line\nThird line");
core::stringc text(Text.c_str());
std::cout << text.c_str() << std::endl;
return Text;
}
int main()
{
core::stringc text(func().c_str());
std::cout << text.c_str() << std::endl;
} // Note that the stringw returned from func() will be implicitly destroyed here
or
Code: Select all
void func(core::stringw & outString)
{
outString = L"First line\nSecond line\nThird line";
core::stringc text(outString.c_str());
std::cout << text.c_str() << std::endl;
}
int main()
{
core::stringw wideString;
func(wideString);
core::stringc text(wideString.c_str());
std::cout << text.c_str() << std::endl;
} // Note that wideSrting will be implicitly destroyed here