wchar_t crashes when return from a function

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • bomberman
    New Member
    • Aug 2010
    • 1

    wchar_t crashes when return from a function

    I have a function like this:

    const wchar_t* getId()
    {
    std::wstring id_w = L"12345678";
    return id_w.c_str();
    }

    int _tmain(int argc, _TCHAR* argv[])
    {
    std::wcout.imbu e(std::locale(" "));
    wprintf(L"This is wchar: %s", getId() );
    }

    It output "This is wchar: ?2345678", The first character is crashed.

    But if I do it without function call, like this, it works fine.
    int _tmain(int argc, _TCHAR* argv[])
    {
    std::wcout.imbu e(std::locale(" "));
    std::wstring id_w = L"12345678";
    wprintf(L"This is wchar: %s", id_w.c_str() );
    }

    Any ideas what is wrong?

    Thanks
  • newb16
    Contributor
    • Jul 2008
    • 687

    #2
    std::wstring id_w = L"12345678";
    this is local variable, it's destroyed after function returns and the pointer to string obtained by c_str() is no longer valid.

    Comment

    Working...