views:

420

answers:

2

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:

  • CP1: 460k
  • CP2:19996k
  • CP3:19996k
  • CP4:16088k

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

+2  A: 

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

Nikola Smiljanić
Hmm, but it seems that at the beginning the program need's only 460k and after creating myList , appending elements, removing elements, and deleting myList, it needs 16088k. So where is over 15000k?
Moomin
Your program allocates additional memory when you append new elements, it then frees this memory when you remove all elements. But the memory manager holds on to this memory and doesn't give it back to the OS.
Nikola Smiljanić
Nice, and if some other app would need that part of memory would it be available for it or memory manager keeps it only for original app? Is there any way to force giving it back to the OS?
Moomin
This is not something you should worry about. In case the system is running low on memory it would probably release it from your program and use it for the program that needs the memory.
Nikola Smiljanić
A: 

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.

extropy