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?.
What you are observing is undefined behavior.
The call to
toLatin1()
creates a temporaryQByteArray
, which is destroyed immediately after that line, since you do not store it. The pointer obtained bydata()
is left dangling and might or might not print something useful.Correct version: