Juriy
Juriy

Reputation: 585

Why const QString& param return bad const char* pointer to data

Find out interesting bug: when I pass const QString& parameter and then get const char* pointer to data that stored within const QString&, pointer points to bad data (some characters that not seemed as I send to function).

LogbookNote LBHasher::makePropsFromPseudoElement(const QString& id)
{
   LogbookNote rv;
   if (m_ctx->currentTrim) {
    const char* charId = id.toLatin1().data();
    ...
    qDebug() << charId;
}

And calling code:

LogbookNote LBHasher::makePropsByNameConvention(QString id)
{
   LogbookNote g;
   if (id.startsWith("_ctx_")) {
       g = makePropsFromPseudoElement(id);
 ...
 }

As you can mention, to calling method id comes as QString, i.e. whole copy of QString object. And thus const QString& can be a strong (not broken, to deleted temporary object, for example) reference.

Why such behavior occurred?

Upvotes: 2

Views: 133

Answers (2)

NathanOliver
NathanOliver

Reputation: 180825

QString::toLatin1 returns a QByteArray by value which means it is a temporary object. That QByteArray is destroyed at then end of that line(full expression) leaving you with a pointer to invalid object and using it is undefined behavior.

Upvotes: 3

Igor Tandetnik
Igor Tandetnik

Reputation: 52581

id.toLatin1() creates a temporary QByteArray instance. You then store a pointer to the buffer managed by that temporary. At the semicolon, the temporary is destroyed, leaving your pointer dangling; using that pointer later exhibits undefined behavior.

Upvotes: 4

Related Questions