Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. Debug-Mode different behaviour with string
Forum Updated to NodeBB v4.3 + New Features

Debug-Mode different behaviour with string

Scheduled Pinned Locked Moved Solved General and Desktop
3 Posts 2 Posters 672 Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • L Offline
    L Offline
    louis
    wrote on last edited by
    #1

    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?

    1 Reply Last reply
    0
    • andrA Offline
      andrA Offline
      andr
      wrote on last edited by
      #2

      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);
      
      
      
      1 Reply Last reply
      4
      • L Offline
        L Offline
        louis
        wrote on last edited by
        #3

        Works! And i understand why ;) thank you!

        1 Reply Last reply
        0

        • Login

        • Login or register to search.
        • First post
          Last post
        0
        • Categories
        • Recent
        • Tags
        • Popular
        • Users
        • Groups
        • Search
        • Get Qt Extensions
        • Unsolved