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



  • 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?



  • 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*?



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


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.