[libpq] Segmentation fault when call PQfinish inside singletone pattern

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

[libpq] Segmentation fault when call PQfinish inside singletone pattern

Ilya Galdin

I'm create singletone class, and want to add inside PGconn object.

This class, in the past, will provide connections to DB.

// postgresql
#include <libpq-fe.h>
//==============================================================================
class TestST
{
public:
  static TestST& getInstance()
  {
    static TestST test;
    return test;
  }
  bool createConnection()
  {
    mConn.reset( PQsetdbLogin("localhost", "5432", NULL, NULL,
                             "test_db", "user_app",
                             "passwd"),
                 &PQfinish); // [SIGSEGV when delete] passing a reference to the destroy function
    return true;
  }

private:
  TestST()
  {

  }
private:
  std::shared_ptr<PGconn> mConn; // smart pointer to postgres connetion object
};

//==============================================================================
int main(int argc, char** argv)
{
  TestST::getInstance().createConnection(); // create singletone and connection

  return 0;
}
//==============================================================================

When singletone is deleted, function PQfinish calls signal Segmentation fault.

But If I move the initialization of mConn to the constructor - it's work. If I build and run on windows (MSVC) - it's work. 

postgres version 9.6.9; OS - Debian 9; gcc version 6.3.0

Faithfully yours Ilya Galdin

Reply | Threaded
Open this post in threaded view
|

Re: [libpq] Segmentation fault when call PQfinish inside singletone pattern

Robert Haas
On Tue, Jul 2, 2019 at 9:32 AM Ilya Galdin <[hidden email]> wrote:
> When singletone is deleted, function PQfinish calls signal Segmentation fault.
>
> But If I move the initialization of mConn to the constructor - it's work. If I build and run on windows (MSVC) - it's work.

I doubt that this is a bug in PostgreSQL. Admittedly, I also don't see
what's wrong with your C++ code.  I tested here and it works OK for
me.  All the same, I suspect the issue is more likely to be there than
in PQfinish, which just closes the connection and frees associated
memory.  If you're getting a segmentation fault inside that function,
a likely reason is that the pointer you're passing to PQfinish is not
valid. You might be able to confirm or refute this theory by running
the failing program inside a debugger. Then, you can get a backtrace
at the point of the segmentation fault, and you can also print out the
values of key variables and see whether, for example, the PGconn looks
mostly OK with maybe one bad pointer someplace, or whether it's all
garbage.

--
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company