Moomin
Moomin

Reputation: 1926

QList memory deallocation

I'm trying to free memory after using QList, but it doesn't seem to work properly. Here's my code:

QList<double> * myList;
myList = new QList<double>;

double myNumber;

cout << "CP1" << endl;
getchar();  // checkpoint 1

for (int i=0; i<1000000; i++)
{
    myNumber = i;
    myList->append(myNumber);
    cout << myList->size() << endl;
}

cout << "CP2!" << endl;
getchar();  // checkpoint 2


for (int i=999999; i>0; i--)
{
    myList->removeLast();
    cout << myList->size() << endl;
}

cout << "CP3!" << endl;
getchar();  // checkpoint 3

delete myList;

cout << "CP4!" << endl;
getchar();  // checkpoint 4

Memory usage:

So it looks like despite removing of elements and deleting myList still large part of memory is being used. I believe there is a way to handle it but I can't find it.

Thanks in advance for any help.

Pawel

Upvotes: 4

Views: 6536

Answers (2)

Viesturs
Viesturs

Reputation: 1691

QList is an array based list. The array expands automatically, but does not shrink automatically. Removing elements from the list does not affect the size of the array.

To trim the array down to the actual size, create a new QList and add the contents to it. Then delete the original list.

Unfortunately looks like there is no convenience method to do this, like the List.TrimExcess() in .NET.

Upvotes: 0

Nikola Smiljanić
Nikola Smiljanić

Reputation: 26873

Memory manager is not required to release the memory your program has allocated. There are no problems in your deallocation.

Upvotes: 3

Related Questions