QSqlDatabase - memory leak
-
qt 5.7 mingw 32bits
#include <qcoreapplication.h> #include <QSqlDatabase> #include <qdebug.h> #include <quuid.h> #include <qsqldatabase.h> #include <qsqlquery.h> bool gExit = false; void handleSignal(int sig) { gExit = true; } void test1() { QString name = QUuid::createUuid().toString(); QSqlDatabase *db = new QSqlDatabase(QSqlDatabase::addDatabase("QOCI", name)); db->setDatabaseName("test"); db->setHostName("localhost"); db->setPort(1521); db->setUserName("system"); db->setPassword("123456"); for (int i = 0; i < 1000; ++i) { if(!db->open()) { qDebug("db->open failed"); delete db; return; } db->close(); qDebug("done %d", i); } delete db; //QSqlDatabase::removeDatabase(name); //unless enable this } int main(int argc, char *argv[]) { signal(SIGINT, handleSignal); QCoreApplication app(argc, argv); test1(); int ret = app.exec(); return ret; }
memory malloc in db.open, but not free in db.close.
-
qt 5.7 mingw 32bits
#include <qcoreapplication.h> #include <QSqlDatabase> #include <qdebug.h> #include <quuid.h> #include <qsqldatabase.h> #include <qsqlquery.h> bool gExit = false; void handleSignal(int sig) { gExit = true; } void test1() { QString name = QUuid::createUuid().toString(); QSqlDatabase *db = new QSqlDatabase(QSqlDatabase::addDatabase("QOCI", name)); db->setDatabaseName("test"); db->setHostName("localhost"); db->setPort(1521); db->setUserName("system"); db->setPassword("123456"); for (int i = 0; i < 1000; ++i) { if(!db->open()) { qDebug("db->open failed"); delete db; return; } db->close(); qDebug("done %d", i); } delete db; //QSqlDatabase::removeDatabase(name); //unless enable this } int main(int argc, char *argv[]) { signal(SIGINT, handleSignal); QCoreApplication app(argc, argv); test1(); int ret = app.exec(); return ret; }
memory malloc in db.open, but not free in db.close.
@Tancen It would be nice to describe the problem instead simply throwing some code...
You don't delete db if you do a return inif(!db->open()) { qDebug("db->open failed"); return; }
Why do you create db on the stack?
QSqlDatabase db;
would be enough.
-
i forget it. but the problem is not about it. you can try and repeat open / close more times.
@Tancen said in QSqlDatabase - memory leak:
you can try and repeat open / close more times.
He knows it.
It tells you that if the base is not opened, you're doing 'return' and this is exactly the problem, 'return' - has finished function and the base itself will not be removed.
for (int i = 0; i < 1000; ++i) { if(!db->open()) { qDebug("db->open failed"); delete db; return; //stop function } db->close(); qDebug("done %d", i); } delete db; //It will not be fulfilled.
-
thanks.
i know he means.
i tested and get memory leak about open/close
my code is only a mini show -
Hi,
No OS guaranties that when you call delete, the memory is returned instantly to said OS. All the more if you are using a tight loop like that.
Note that you are also not using the QSqlDatabase API correctly.