Project

General

Profile

Memory Leak in Postgres Dbo backend

Added by Gianluca Sorrentino about 15 years ago

Hi,

the Wt::Dbo::backend::Postgres class has only a constructor: Postgres::Postgres( string & db ) wich establish a connection to the RDBMS or raise an exception in case of failure.

Since throwing an exception in a constructor avoids the subsequent call to the destructor, the constructor should release its already assigned resources before raising the error in order to avoid memory leaks.

This is the current function: bool Postgres::connect(const std::string& db { src/Wt/Dbo/backend/Postgres.C: 476 }

Every time the backend goes in exception during obj creation, the PGconn obj is not deleted (via PQfinish ).

When backend obj will be deleted, its destructor will not be called, causing the leak of the memory occupied by the PGconn obj.

bool Postgres::connect(const std::string& db)
{
  connInfo_ = db;
  conn_ = PQconnectdb(db.c_str());

  if (PQstatus(conn_) != CONNECTION_OK)                     
    throw PostgresException("Could not connect to: " + db); // IT'S USELESS TO SEND BACK THE CONNECT STRING WITHOUT THE REAL FAIL REASON


  return true;
}

This is the connect function modified to delete the PGconn structure in case of failure and to give back the DBMS connect error. In every test this code has not produced any memory leak.

bool Postgres::connect(const std::string& db)
{
  connInfo_ = db;
  conn_ = PQconnectdb(db.c_str());

  if (PQstatus(conn_) != CONNECTION_OK){                     
    string error = PQerrorMessage(conn_);                      // SAVE ERROR OF conn_ BEFORE RELEASING IT
    PQfinish(conn_);                                           // FREE conn_ RESOURCES
    throw PostgresException("Could not connect to: " + error); // SEND BACK THE REAL FAIL REASON
  }

  return true;
}

Every memory test has been done using valgrind.

Please check and update the code, thanks :)

Moreover i suggest to implement a Postgres::Postgres(void) constructor to allow normal memory allocation and deallocation mechanism, leaving connect method public giving the possibility to connect later.

Regards

Gianluca Sorrentino


Replies (1)

RE: Memory Leak in Postgres Dbo backend - Added by Koen Deforche about 15 years ago

Hey,

Thanks for the suggestions. It'll be part of the next release!

Regards,

koen

    (1-1/1)