Search code examples
c++qtqfile

Heap corruption: what happens if I don't close a (Q)file?


I open a (Q)file in a function but I forget to close it (because I wronged to write the code). What happens to the memory, the buffer and my informations?

Example (C++):

void myFunction(QString path)
{
    QFile file(path);
    file.open(...);

    if( _myWrongCondition_ )
    {
        informations = // do something
        writeInformationToFile(file,informations);
        file.close;
    }
}

Assume that I call this function in a while. Could this provoke an heap corruption?

Thanks in advance!


Solution

  • No, to forget to release a resource (such as a file) won't corrupt anything.

    If the acquired resource is dynamically allocated memory simply it won't be released and you'll have a memory leak.

    In this case if you omit to call the close() function nothing will happen at all because file is stack allocated, compiler will emit the code to call its destructor when it'll go out of scope (at the end of the function, in that code).