Re: std::List doesn't releases the memory ...
On Jul 6, 9:32 am, RV <rahul.va...@gmail.com> wrote:
Hi,
I have compiled the following source code on SuSE linux with g++
compiler version 3.4.3.
#include <iostream>
#include <list>
void PopulateList(std::list<int> & li, int numitr)
{
for(int i = 0; i < numitr; i++){
li.push_back(i);
}
}
void testList()
{
char ch;
int numitr;
std::list<int> li;
std::cout << "Enter any charater to continue : Before
Populating std::list<int> : take memory reading: ";
std::cin >> ch;
std::cout << "How many iteration: ";
std::cin >> numitr;
PopulateList(li, numitr);
std::cout << "Press any charater to continue : After
Populating std::list<int> : take memory reading: ";
std::cin >> ch;
li.clear();
std::cout << "Press any character to continue : After
clearing std::list<int> : take memory reading: ";
std::cin >> ch;
}
int main()
{
while(1) {
testList();
std::cout << "==>\n";
std::cout << "==> End of while\n";
std::cout << "==>\n";
} // End of While
}
OBSERVATION:
The multiple iteration of while loop doesn't release the memory
occupied by the std::list
Is this a bug with std::List or incorrect usage of it?
The same behaviour is not observed with std::vector?
Does anyone knows the solution for this?
Thanks and With Warm Regards,
-RV
It has nothing to do with std::list or std::vector.
It has everything to do with the implementation of malloc on
your system. I'm guessing you're using glibc for that.
And I'm also guessing that the glibc that's on your
system is using a variation on ptmalloc.
That means that malloc/free algorithm will try to cache
small memory allocations for specific thread. In other words,
when std::list calls Allocator::deallocate(), which in turn
will call ::operator delete() which in turn will call free(),
the memory isn't really being freed, but rather cached for
further use by the same thread.
Your own test app shows that - no matter how many times you
run your main loop, the amount of memory used will never be
more than what the very first loop has created. Starting with
2nd loop onwards, the memory will be re-used.
vectors are different because vectors have to allocate contiguous
memory and ptmalloc will free contiguos memory back to the
system more eagerly.
Do a different test - instead of using std::list, just write your
own linked list implementation and use new to create nodes.
You'll notice the same pattern - even if you free all your nodes,
the memory won't be reclaimed by the system.
If you're wandering how you can control memory reclamation - welcom
to the club. I ended up using google's tcmalloc. You can also
used Hoard allocator, but that's not opensource.
Andy.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]