Search code examples
c++qtqdebug

QString formatting will not work qDebug


I try to avoid mixed QString and char* types in a QT program. I have a conversation function that returns a pointer of the data inside the QString, but I get very strange results. Whats wrong with this code?

Compiler and environment gcc (Debian 4.9.2-10) 4.9.2 Flags via qmake: QMAKE_CXXFLAGS += -std=c++11

Code snippet:

#include <QCoreApplication>
#include <iostream>
#define  PCH(m) ( m.toAscii().data() )

// get the pointer short scripted
const char* CH(QString msg) {
   const char* res = msg.toAscii().data();
   return res;
}

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);

    const QString qformat = "%s does not work!";
    const QString qvalue  = "embedding";

    // Works not
    qDebug(CH(qformat), CH(qvalue));   

    // Works
    qDebug(qformat.toAscii().data(), qvalue.toAscii().data());

    // Works too but macro
    qDebug(PCH(qformat), PCH(qvalue));   

    return app.exec();
}

Results

%s does not work! does not work!

embedding does not work!

embedding does not work!

Solution

  • Here you are copying QString to function, and return pointer to already destroyed data inside function. This is known undefined behavior, since you are returning pointer to garbage. Return QString.

    const char* CH(QString msg) {
        const char* res = msg.toAscii().data();
        return res;
    }