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)));