#38 Unsafe use of std::string

closed-fixed
None
5
2009-02-18
2008-01-03
Anonymous
No

In Common.cpp (SVN:581) there are a couple of instances of returning pointers derived from temporary strings. This is unsafe since the destructor for sResult will be called before the caller can use the returned pointer, thus invalidating it. This causes a crash on startup when built with Visual C++ 2005.

const char* GetAppFullName()
{
string sResult = string("FUPPES - Free UPnP Entertainment Service ") + fuppes_get_version();
return sResult.c_str();
}

const char* GetAppShortName()
{
string sResult = string("FUPPES ") + fuppes_get_version();
return sResult.c_str();
}

Cheers

Tim (spam@twistedfury.com)

Discussion

  • Ulrich Völkel

    Ulrich Völkel - 2008-01-04

    Logged In: YES
    user_id=1228080
    Originator: NO

    Ouch, really embarrassing. You are absolutely right.

    How does VS handle something like this?

    std::string GetStr()
    {
    string sResult;
    sResult = "test";
    return sResult.c_str();
    }

    Thanks!
    - Uli

     
  • Ulrich Völkel

    Ulrich Völkel - 2008-01-04
    • assigned_to: nobody --> u-voelkel
     
  • Nobody/Anonymous

    Logged In: NO

    That would work, but better to get rid of the c_str() on return or you'll go via another string constructor.
    e.g.)
    string GetAppFullName()
    {
    return string("FUPPES - Free UPnP Entertainment Service ") + fuppes_get_version();
    }

    It's also safe to pass GetAppFullName().c_str() as a function argument, since the temporary string returned will outlive the function call!

    Cheers

    Tim

     
  • Ulrich Völkel

    Ulrich Völkel - 2009-02-18

    fixed in svn 630

     
  • Ulrich Völkel

    Ulrich Völkel - 2009-02-18
    • status: open --> closed-fixed
     

Log in to post a comment.

Get latest updates about Open Source Projects, Conferences and News.

Sign up for the SourceForge newsletter:





No, thanks