I have bunch of methods:
bool PGConnection::connect() {
try
{
conn = new pqxx::connection(
"user=temp "
"host=xxxx "
"password=xx "
"dbname=temp");
}
catch (const std::exception &e)
{
std::cerr << e.what() << std::endl;
return false;
}
return true;
}
//Disconnect from db
bool PGConnection::disconnect() {
if ( conn->is_open()) {
std::cout<<"try disconnect"<<std::endl;
conn->disconnect();
return true;
}
return false;
}
PGConnection::~PGConnection() {
if ( conn != NULL) {
delete conn;
}
}
When disconnect or class destructor is called, it results in segmantation fault. (When i comment out disconnect part below it happens when destructor is called.)
int main () {
PGConnection pgConn("xxx","xxx");
pgConn.connect();
pgConn.disconnect();
return 0;
}
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7ba4852 in pqxx::connection_base::is_open() const () from /usr/lib/libpqxx-3.1.so
(gdb) bt
#0 0x00007ffff7ba4852 in pqxx::connection_base::is_open() const () from /usr/lib/libpqxx-3.1.so
#1 0x00000000004019d3 in PGConnection::disconnect (this=0x7fffffffe600) at pgconnection.cpp:42
#2 0x000000000040269e in main () at main.cpp:8
(gdb) frame 2
#2 0x000000000040269e in main () at main.cpp:8
8 pgConn.disconnect();
(gdb) print pgConn
$1 = {conn = 0x3}
gdb with out calling disconnect:
(gdb) bt
#0 0x00007ffff7ba5fdb in pqxx::connection_base::close() () from /usr/lib/libpqxx-3.1.so
#1 0x0000000000401d3e in pqxx::basic_connection<pqxx::connect_direct>::~basic_connection (this=0x3,
__in_chrg=<optimized out>) at /usr/include/pqxx/basic_connection.hxx:74
#2 0x0000000000401a3d in PGConnection::~PGConnection (this=0x7fffffffe600, __in_chrg=<optimized out>)
at pgconnection.cpp:57
#3 0x00000000004026a3 in main () at main.cpp:11
(gdb) frame 2
#2 0x0000000000401a3d in PGConnection::~PGConnection (this=0x7fffffffe600, __in_chrg=<optimized out>)
at pgconnection.cpp:57
57 delete conn;
(gdb) print conn
$1 = (pqxx::connection *) 0x3
(gdb)
It's hard to say without seeing the constructor for PGConnection
. In particular, the constructor should always set conn=NULL
.
I'd also recommend that the line that currently says
if ( conn->is_open()) {
Should instead be
if (conn && conn->is_open()) {
I strongly suspect that your conn
member is not being properly initialized.
Better still would be to redesign the class so that you eliminate the use of new
and delete
entirely if you can. If you do so, it would be a much better way of solving the problem. There's not likely to be much reason for PGConnection
to exist unless it's about to connect to something, so the constructor could also contain the code to instantiate a pqxx::connection
.