[Interest] QDataStream null terminated string / Bug or expected behavior?

Thiago Macieira thiago.macieira at intel.com
Thu Feb 9 22:09:34 CET 2017


On quinta-feira, 9 de fevereiro de 2017 18:18:07 PST Etienne Sandré-Chardonnal 
wrote:
> Dear all,
> 
> I just found out a bug in my code which was due to the way I wrote/read
> from QDataStream.
> 
> I write a string like that in one program, from a std::string. This uses
> the null-terminated char* overload of << :
> 
> std::string str("test");
> stream << str.c_str();
> 
> I read the data like that in another program:
> 
> QByteArray ba;
> stream >> ba;
> 
> Then ba.size() returns 5 and it contains the null character. Therefore,
> comparing it to "test" failed.
> 
> In the documentation I cannot find a QByteArray & overload of operator >>.
> QByteArray is not supposed to be castable to char*. What is happening here?

The two operators are there:
Q_CORE_EXPORT QDataStream &operator<<(QDataStream &, const QByteArray &);
Q_CORE_EXPORT QDataStream &operator>>(QDataStream &, QByteArray &);

And they're documented:
http://doc.qt.io/qt-5/qbytearray.html#operator-lt-lt
http://doc.qt.io/qt-5/qbytearray.html#operator-gt-gt

The bug is in your code for marshalling one type and demarshalling another. 
That's not guaranteed to work. The behaviour of the two functions is 
different. See for yourself:

https://code.woboq.org/qt5/qtbase/src/corelib/tools/
qbytearray.cpp.html#_ZlsR11QDataStreamRK10QByteArray
https://code.woboq.org/qt5/qtbase/src/corelib/io/
qdatastream.cpp.html#_ZN11QDataStreamlsEPKc

-- 
Thiago Macieira - thiago.macieira (AT) intel.com
  Software Architect - Intel Open Source Technology Center




More information about the Interest mailing list