我使用QT 4.5.3訪問SQLite數據庫,就像這樣:打開數據庫導致內存泄漏
class db : private boost::noncopyable
{
public:
db(QString file) : filename(file),
realdb(NULL),
theConnectionEstablished(false)
{
}
~db()
{
if (NULL != realdb.get())
{
realdb.reset(NULL);
}
if (theConnectionEstablished)
{
QSqlDatabase::removeDatabase("ConnName");
}
}
void open()
{
realdb.reset(new QSqlDatabase(QSqlDatabase::addDatabase("QSQLITE", "ConnName")));
theConnectionEstablished = true;
// open the db
realdb->setDatabaseName(filename);
if (! realdb->open())
{
const QSqlError dbError = realdb->lastError();
const QString errorDesc = "Error opening the database : " + filename +
"\nDatabase error : " + dbError.databaseText() +
"\nDatabase driver error : " + dbError.driverText();
// DatabaseError is a class type which accepts the std::string for logging purposes
throw DatabaseError(errorDesc.toStdString());
}
}
const QString filename;
std::auto_ptr<QSqlDatabase> realdb;
bool theConnectionEstablished;
};
現在,如果我嘗試測試這種情況下,像這樣(我使用cxxtest) :
void test_failed_connection()
{
db obj("/");
TS_ASSERT_THROWS(obj.open(), DatabaseError);
}
我得到的valgrind報告內存泄漏:
<error>
<unique>0x5b</unique>
<tid>1</tid>
<kind>Leak_DefinitelyLost</kind>
<what>986 (384 direct, 602 indirect) bytes in 1 blocks are definitely lost in loss record 23 of 23</what>
<leakedbytes>986</leakedbytes>
<leakedblocks>1</leakedblocks>
<stack>
<frame>
<ip>0x4006D3E</ip>
<obj>/opt/valgrind341/lib/valgrind/x86-linux/vgpreload_memcheck.so</obj>
<fn>malloc</fn>
<dir>/home/slawomir/valgrind-3.4.1/build/valgrind-3.4.1/coregrind/m_replacemalloc</dir>
<file>vg_replace_malloc.c</file>
<line>207</line>
</frame>
<frame>
<ip>0x67FADC4</ip>
<obj>/usr/lib/libsqlite3.so.0.8.6</obj>
<fn>sqlite3_malloc</fn>
</frame>
<frame>
<ip>0x67FAF13</ip>
<obj>/usr/lib/libsqlite3.so.0.8.6</obj>
</frame>
<frame>
<ip>0x6816DA3</ip>
<obj>/usr/lib/libsqlite3.so.0.8.6</obj>
</frame>
<frame>
<ip>0x68175FD</ip>
<obj>/usr/lib/libsqlite3.so.0.8.6</obj>
<fn>sqlite3_open16</fn>
</frame>
<frame>
<ip>0x40DDEF9</ip>
<obj>/usr/lib/qt4/plugins/sqldrivers/libqsqlite.so</obj>
</frame>
<frame>
<ip>0x7F34AE0</ip>
<obj>/usr/lib/libQtSql.so.4.5.2</obj>
<fn>QSqlDatabase::open()</fn>
</frame>
</frame>
</stack>
</error>
有誰知道如何解決此泄漏?
@DumbCode我不想優化任何東西,但我正在嘗試單元測試我的代碼。問題是如何在打開數據庫出現問題時測試案例。正如您在示例中所看到的,我傳遞「/」(根目錄)作爲數據庫名稱來模擬該情況。 – 2010-12-01 10:17:55