Debug-Mode different behaviour with string



  • Hi,

    i found an old code-snipplet in our project:

      QString version = "abcdefghi";
      const char* cVersion = version.toStdString().c_str();
    
      qDebug() << cVersion;
      qDebug() << version;
    

    Output in normal run is:
    abcdefghi
    "abcdefghi"

    Output in Debug-mode is:
    ??????????????????????????????????????????????????????????????5???f >
    "abcdefghi"

    Compiled both as Debug and tried Qt 5.1.1 and Qt 5.6.0 using GNU gdb 7.8 MinGw 4.9.2 32 bit.
    Also the last part always differs a little. So it shall be a pointer-problem. But what bugs me is the different behaviour in running and debug-mode.

    Is there a reason for this?



  • This code is broken.

    version.toStdString() creates a temporary std::string object, for which you use .c_str() to get a pointer to the internal storage. At the end of the full expression (essentially the ';' in that line) all temporaries from this full expression are destroyed. I.e. the .c_str() result now points to some released(!) memory. Any access to that invokes undefined behaviour, and you notice exactly that.

    The correct way is to keep the temporary value alive:

      QString version = "abcdefghi";
      std::string sVersion = version.toStdString();
      const char* cVersion = sversion.c_str();
    

    or, better, to be explicit about the encoding change that's implicit in the toStdString()

      QString version = "abcdefghi";
      QByteArray sVersion = version.toUtf8(); // or .toLatin1(), or .toLocal8Bit(), or..
      const char* cVersion = sversion.constData);
    
    
    


  • Works! And i understand why ;) thank you!


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.