Is it possible that QFile::size() and QFile::readAll().size() differ for certain special files?

306 Views Asked by At

Seeing a weird crash due to read access violation. Here is the minimal code:

struct MyFile : QFile
{
  ...
  string read ()
  {
    QByteArray content;
    if(<something>)
      content = QFile::readAll();
    ...
    string buffer(QFile::size(), 0);
    if(content.isEmpty())
    {
      QFile::seek(offset);
      QFile::read(&buffer[0], buffer.size());
    }
    else
      ::memcpy(&buffer[0], content.data(), buffer.size());
      //                   ^^^^ 40034      ^^^^ 42690
    return buffer;
   }
}

Here it's trying to read a .png file. Somehow the QFile::size() returns 42690, while the QFile::readAll() which is stored in content has a size of 40034.

Unfortunately the filename is not handy to verify the actual size. Writing test code for text or png files, it always gives proper results.

How is that possible?
Below is a debug frame for reference:

enter image description here

1

There are 1 best solutions below

2
Alexander Dyagilev On

You code does not take the current file's seek position into account. Thus, in case there were some read operations already, it will crash, because QFile::readAll will return only a part of the file (from the current seek position till the end of file).

The other possibility is the use of QIODeviceBase::Text as mentioned in comments, but you're not using it, so it's not the case.