Weird behavior of QString::toLocal8Bit().data()

Look at this simple code:

QString s="abcd";
char * ts=s.toLocal8Bit().data();
QMessageBox::information(NULL,"length",QString("s length:%1, ts length:%2").arg(s.length()).arg(strlen(ts)));

What do you think about the length of s and ts? Are they both 4? No, on my machine, the length of the QString s is 4(correct) and the length of ts is 8174(surprise!) Why?

The reason is on the third line, the pointer ts does not point to the buffer of s or any byte array; it actually points to an unallocated memory. This is because the pointer returned by the data() function of QByteArray only remains valid when the QByteArray object is valid, while s.toLocal8Bit() returns a temporary QByteArray object that is only valid at the statement(the second line). After line 2, the temporary QByteArray object is destroyed thus the pointer pointing to its original memory buffer becomes invalid. You should save the object returned by s.toLcal8Bit() to avoid the destruction.

QString s="abcd";
QByteArray ba=s.toLocal8Bit();
char * ts=ba.data();
QMessageBox::information(NULL,"length",QString("s length:%1, ts length:%2").arg(s.length()).arg(strlen(ts)));

 

 

Did you like this?
Tip admin with Cryptocurrency

Donate Bitcoin to admin

Scan to Donate Bitcoin to admin
Scan the QR code or copy the address below into your wallet to send some bitcoin:

Donate Bitcoin Cash to admin

Scan to Donate Bitcoin Cash to admin
Scan the QR code or copy the address below into your wallet to send bitcoin:

Donate Ethereum to admin

Scan to Donate Ethereum to admin
Scan the QR code or copy the address below into your wallet to send some Ether:

Donate Litecoin to admin

Scan to Donate Litecoin to admin
Scan the QR code or copy the address below into your wallet to send some Litecoin:

Donate Monero to admin

Scan to Donate Monero to admin
Scan the QR code or copy the address below into your wallet to send some Monero:

Donate ZCash to admin

Scan to Donate ZCash to admin
Scan the QR code or copy the address below into your wallet to send some ZCash:
Posted in

Leave a Reply