When I create an array of connections to psql database using pqxx, connections create successfully and they are in the array. But when I'm going to use one connection it gives me the following error. The way i created the array is also mentioned below. Can anyone tell me the reason for this.
for(int i=0;i<10;i++)
{
connection c("dbname=test user=postgres password=abc123\
hostaddr=127.0.0.1 port=5432");
conList[i]=&c;
}
for (int j=0;j<10;j++)
{
cout<<conList[j]->is_open()<<endl; // this returns 0
}
conList[0]->activate(); // at this point it gives the following error
terminate called after throwing an instance of 'pqxx::broken_connection' what(): Connection to database failed Aborted
You are storing address of local variable c
in conList
, after first for
loop, those local variables are released, conList
stores dangling pointers only, invoke function call to dangling pointers has undefined behavior.
for(int i=0;i<10;i++)
{
connection c("dbname=test user=postgres password=abc123\
hostaddr=127.0.0.1 port=5432");
conList[i]=&c; // c is local variable
} // c is released here
for (int j=0;j<10;j++)
{
cout<<conList[j]->is_open()<<endl; // undefined behavior
}
conList[0]->activate(); // undefined behavior
Consider below change?
store value instead of pointer in conList
for(int i=0;i<10;i++)
{
connection c("dbname=test user=postgres password=abc123\
hostaddr=127.0.0.1 port=5432");
conList[i] = c; // make a copy of c
}
for (int j=0;j<10;j++)
{
cout<<conList[j].is_open()<<endl;
}
conList[0].activate();