处理连接对象时出现分段错误
Segmentation fault when dealing with connection object
我有很多方法:
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;
}
}
当调用disconnect或类析构函数时,会导致分段故障。(当我在下面注释掉断开连接的部分时,它发生在调用析构函数时。)
int main () {
PGConnection pgConn("xxx","xxx");
pgConn.connect();
pgConn.disconnect();
return 0;
}
带disconnect()的gdb调用:
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:
(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)
很难说没有看到PGConnection
的构造函数。特别是,构造函数应该始终设置conn=NULL
。
我还建议目前显示的行
if ( conn->is_open()) {
应该是
if (conn && conn->is_open()) {
我强烈怀疑您的conn
成员没有正确初始化。
更好的方法是重新设计类,以便尽可能完全消除new
和delete
的使用。如果你这样做,这将是解决问题的更好方法。除非PGConnection
即将连接到某个东西,否则它不太可能存在,因此构造函数也可以包含实例化pqxx::connection
的代码。
相关文章:
- 在某些循环内使用vector.push_back时出现分段错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 当我的阵列太大时出现分段错误
- 分段错误当我试图运行程序时出错
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 尝试使用集合函数时出现分段错误
- 我无法缩小此分段错误的原因
- g++的分段错误(在NaN上使用to_string两次时)
- 我是如何在这段代码中出现分段错误的
- 创建结构的数组时遇到分段错误
- 在c++中键入向量中的所有值后,得到分段错误(核心转储)
- 在 c++ 中实现 Trie 时出现分段错误
- 为什么 fstream 在打开带有格式的文件时会导致分段错误?
- 为什么我遇到分段错误?
- 动态类的分段错误(家庭作业问题)
- 分段错误 - 读取初始化指针的数组
- 如何摆脱C ++中的分段错误错误?
- 使用 CTYPE 时出现分段错误
- 为什么代码给出分段错误?