Different results for QString to const char*

843 Views Asked by At

I have a code snippet to test a code bug.

    #include <QCoreApplication>
    #include <QDebug>

    int main(int argc, char *argv[])
    {
        QCoreApplication a(argc, argv);
        QString name = QString("Lucy");
        QString interest = QString("Swimming");

        const char* strInterest = interest.toLatin1().data();
        const char* strName = name.toLatin1().data();

        qDebug()<<"QName: "<<name<<" QInterest: "<<interest;
        qDebug()<<"Name: "<<strName<<" Interest: "<<strInterest;

        return a.exec();
    }

The result on macOS: QName: "Lucy" QInterest: "Swimming" Name: Lucy Interest: .

The result on ubuntu: root@:test$ ./testCharP QName: "Lucy" QInterest: "Swimming" Name: Interest: .
As you can see, the converted buffer does not be saved as a const value, what about the problem? Also, there are some differences between these two OS, what is the cause maybe?.

2

There are 2 best solutions below

0
On BEST ANSWER

What you are observing is undefined behavior.

The call to toLatin1() creates a temporary QByteArray, which is destroyed immediately after that line, since you do not store it. The pointer obtained by data() is left dangling and might or might not print something useful.

Correct version:

const QByteArray& latinName = name.toLatin1();
const char* strName = latinName.data();
3
On

The problem is that the toLatin1 function returns a QByteArray object, and by not saving this object it will be temporary and be destructed once the assignment have been done.

That means your pointer points to some data that no longer exists, and dereferencing it will lead to undefined behavior.