0

I have the following very simple code

#include <QCoreApplication>

#include <QDebug>
#include <QString>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QString b1("Key");
    char *k = b1.toUtf8().data();
    QString b2(argv[1]);
    char *v = b2.toUtf8().data();

    qDebug() << "Key[" << b1.toUtf8().data() << "] value[" << b2.toUtf8().data() << "]";
    qDebug() << "Key[" << k << "] value[" << v << "]";

    return a.exec();
}

When I run the executable passing one argument to the command line (for example Ops) I get the following result

Key[Key] value[Ops]
Key[O] value[en_US.UTF-8]

I can't understand why. Could anyone cast a light on this mistery?

Thank you in advance

ulix

  • 1
    In `char *k = b1.toUtf8().data()` the call `b1.toUtf8()` returns a temporary `QByteArray`. You then call `data()` against that temporary but use the result *after* the temp`QByteArray` has had its destructor invoked. Hence you have undefined behaviour. Almost certainly a dupe somewhere. – G.M. Dec 28 '22 at 13:52

0 Answers0