Possible Duplicate:
Can a local variable's memory be accessed outside its scope?
I saw a function when doing some code review.
wchar_t* GetString(HINSTANCE hInstance, UINT SID)
{
wchar_t buf[2048] = {0};
LoadStringW(hInstance, SID, buf, sizeof(buf)/sizeof(wchar_t));
return &buf[0];
}
void SomeWork()
{
std::wstring str( GetString(hInst, 123) );
}
I thought buf should be destroyed right after function return,
so the pointer &buf[0] might be invalid.
But it seems work fine, how does it work?
And is it a fine design?
Thanks.
Your thoughts are 100% correct.
It “works” because the part of the call stack that holds the
bufarray just happened to not have its contents written over by the time you actually use it.But this is undefined behavior, and undefined behavior means anything can happen, and that can include “summoning an Armageddon” and/or “working just fine”. You just got lucky this time.
No, it’s a terrible design. Fortunately it has a simple fix: just return the
std::wstringitself.All non-stupid C++ compilers will optimize away the temporaries in this case, so this code has no performance penalty in practice. In fact, the Visual C++ compilers will optimize this case even when you turn off all optimizations.
This specific optimization is called return value optimization (RVO). If your C++ compiler doesn’t do RVO even when set at its highest optimization level, get another one.