Uploaded image for project: 'Qt'
  1. Qt
  2. QTBUG-79059

Postgres SQL plugin leaks memory when failing to convert QByteArray



    • Type: Bug
    • Status: Closed
    • Priority: P2: Important
    • Resolution: Won't Do
    • Affects Version/s: 5.7, 5.13.1
    • Fix Version/s: None
    • Component/s: SQL Support
    • Labels:
    • Environment:
      Windows 8.1 and 10 using Visual Studio 2013.5
    • Platform/s:


      The Postgres SQL plugin leaks memory under a specific situation. The whole thing takes place in qsql_psql.cpp:1543, QPSQLDriver::formatValue.

      The Postgres SQL plugin converts QByteArray to QString when executing a query. During the conversion special characters in the QByteArray are escaped using the function PQescapeByteaConn or PQescapeBytea from libpq. The result of either function is stored at a char array, the pointer then passed to the QLatin1String constructor. After successfully creating the QString, the memory at the pointer gets freed. If the construction of the QString fails, the memory at the pointer is not freed at all.

      Construction of the QString can fail, if the QByteArray is too large: QString and QByteArray allow for 2GB of data but Postgres' escape functions might add extra characters, resulting in fewer bytes one can savely provide when executing a query. On Windows platforms (VS2013) an std::bad_alloc exception is thrown, which is not caught by the Postgres SQL plugin, leaving the converted bytes unfreed (possible several hundert megabytes). The query is not executed and the calling function doesn't have a chance to free the escaped bytes.

      Our proposal is to catch any exception, free the escaped bytes and rethrow the exception. A patch is attached and a MWE, too.
      We didn't test this behaviour and patch on other platforms or compilers than Windows 8.1, 10 and Visual Studio 2013.
      The memory leak is present in dev and all versions from at least 5.7 on.


        1. main.cpp
          0.8 kB
        2. qsql_psql_mem_leak.diff
          0.9 kB
        For Gerrit Dashboard: QTBUG-79059
        # Subject Branch Project Status CR V



            mabrand Mark Brand
            tkoeneke tkoeneke
            1 Vote for this issue
            5 Start watching this issue



                Gerrit Reviews

                There is 1 open Gerrit change