Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. [SOLVED] Does QFile::read automatically allocate extra space for buffer
Forum Updated to NodeBB v4.3 + New Features

[SOLVED] Does QFile::read automatically allocate extra space for buffer

Scheduled Pinned Locked Moved General and Desktop
3 Posts 2 Posters 2.6k Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • S Offline
    S Offline
    sayem.bd
    wrote on last edited by
    #1

    Hi,

    I have a function which reads a file and then assigns the content of it in a buffer -

    @long QtFileManager::readFile(const char *fileName, char *buffer, long maxLength)
    {
    if(maxLength <= 0)
    return maxLength;

    QFile file&#40;getFilePathHome(fileName&#41;&#41;;
    bool wasClosed = false;
    if(!file.exists())
        return 0;
    if(!file.isOpen())
    {
        file.open(QIODevice::ReadOnly);
        wasClosed = true;
    }
    
    long length = file.size();
    length = qMin(length, maxLength);
    long dataRead = file.read(buffer, length);
    
    if(wasClosed)
        file.close();
    
    return dataRead;
    

    }@

    Now I am calling this method like this -
    @char data[5];
    long retVal = fileManager->readFile("testFile.txt", data, 19);
    qDebug() << "Retval: " << retVal;@

    and it works! My program doesn't crash. It returns 19 as return value. Shouldn't it create some sorts of run-time exception or something like that since my buffer size is of only 5 characters? What is happening here?

    1 Reply Last reply
    0
    • A Offline
      A Offline
      andre
      wrote on last edited by
      #2

      Nope, it will just be a plain old buffer overrun. You know, the ones you prevent by not using unchecked buffers like this at all. Qt cannot help you with that, as it has no way of knowing how big that buffer really is.

      Why don't you just use a QByteArray instead of a char*?

      1 Reply Last reply
      0
      • S Offline
        S Offline
        sayem.bd
        wrote on last edited by
        #3

        Thank you for your reply, I get it now (silly me!)............

        1 Reply Last reply
        0

        • Login

        • Login or register to search.
        • First post
          Last post
        0
        • Categories
        • Recent
        • Tags
        • Popular
        • Users
        • Groups
        • Search
        • Get Qt Extensions
        • Unsolved