4

I am learning about c++ and I need a little advice on how to clean up memory when not using pointers.

I have a background Blackberry 10 app which has a memory limit of 3MB before it gets stopped, my app is being stopped because of hitting this limit and I am having trouble finding figuring out why.

I have narrowed down the increasing of memory to a function - if I don't call this function the memory doesn't increase.

The function uses QVariant, QVariantList, QVariantMap, QString which are declared outside the function when the class is created (i.e QVariantMap map), before I access these objects in the function I call .clear() on each of them which I am of the understanding should clean up the memory held, I am also using int in the function which are also declared outside of it.

The function is quite large and is calling other functions so I have provided a snippet below of what I am doing in case it is obviously wrong to others.

bindings.clear();
bindings["name"] = name;
result.clear();
result = sqlda->execute(sqlQueryz, bindings);
if (!sqlda->hasError()) {

    if( !result.isNull() ) {
        list.clear();
        list = result.value<QVariantList>();
        recordsRead = list.size();

        for(int iii = 0; iii < recordsRead; iii++) {
            map.clear();
            map = list.at(iii).value<QVariantMap>();

Any help appreciated.

  • 1
    How many records do you read (`recordsRead` variable)? btw qt project recomment a [list of Tools for Profiling and Memory Checking](http://qt-project.org/wiki/Profiling-and-Memory-Checking-Tools). Try Massi, which is on this list. – UmNyobe Oct 16 '14 at 10:13
  • recordsRead is showing as 1 which is correct as there is only one row in the database. – Anthony1234 Oct 16 '14 at 10:39
  • 2
    You're not the only one with this problem: http://supportforums.blackberry.com/t5/Native-Development/Headless-Apps-Databases-and-Memory/m-p/2985760 – Bojan Kogoj Oct 16 '14 at 10:52
  • 1
    Clearing a list only destructs the objects stored by the list. So if `result` and `list` store pointers to objects, the pointers will be forgotten, but the associated objects will still exist. This might lead to memory leaks – jmajnert Nov 14 '14 at 22:31

1 Answers1

1

calling .clear() on a QList or on a QMap clears the list but does not free the objects in the list, so for example if you have:

QList<QObject *> list;
QObject *c = new QObject();
c->setObjectName("object_a");
list.append(c);

QObject *b = new QObject();
b->setObjectName("object_b");
list.append(b);

qDebug() << list.count();   //here you get 2
list.clear();
qDebug() << list.count();   //here you get 0;

qDebug() << a->objectName(); // Here you get "object_a"

This means that after the .clear() your ojects are still living in memory

What you should do when you want to really get rid of all the objects in the list is:

while (list.count() > 0)
    delete list.takeFirst();

and here list.clear() is redundant.

Marco
  • 1,952
  • 1
  • 17
  • 23