memory usage problem

F

fishscience

I have a problem about memory usage. The code is as below:
#include <list>

int main(int argc, char* argv[])
{
{
std::list<void*> ptr_list;
{
for (int i=0; i<9368; i++)
{
size_t size = 10044;
void* p = ::malloc (size);
ptr_list.push_back (p);
}

for (std::list<void*>::iterator i=ptr_list.begin(); i!= ptr_list.end();
i++)
{
void* p=(*i);
::free (p);
}
}
ptr_list.clear();
}
return 0;
}

When all elements in list are freed, the application still have about 30M
memory. After clear function is called, most of memory is freed. However,
the application will have 300k more than the beginning. I think all
allocated memory should be released after list is cleared. The question
is:
1. Why does list still have 30M even if all elements are freed?
2. Why does this program take up 300k more than the beginning?

Test environment:
Windows XP
VS 2005
 
M

mlimber

I have a problem about memory usage. The code is as below:
#include <list>

int main(int argc, char* argv[])
{
{
std::list<void*> ptr_list;
{
for (int i=0; i<9368; i++)
{
size_t size = 10044;
void* p = ::malloc (size);
ptr_list.push_back (p);
}

for (std::list<void*>::iterator i=ptr_list.begin(); i!= ptr_list.end();
i++)
{
void* p=(*i);
::free (p);
}
}
ptr_list.clear();
}
return 0;

}

When all elements in list are freed, the application still have about 30M
memory. After clear function is called, most of memory is freed. However,
the application will have 300k more than the beginning. I think all
allocated memory should be released after list is cleared. The question
is:
1. Why does list still have 30M even if all elements are freed?
2. Why does this program take up 300k more than the beginning?

Test environment:
Windows XP
VS 2005

In standard C++ terms, I would expect your code to behave as you are
expecting: all of the malloc'ed memory is freed in your for loop, and
the list's overhead is freed with list::clear(). However, measuring
memory usage can be tricky and deceptive (you're not using the task
manager for this purpose, are you?) -- not to mention platform-
specific, which makes it off-topic here (http://www.parashift.com/c++-
faq-lite/how-to-post.html#faq-5.9). For more direct help, you'll want
to ask in a group dedicated to your platform or tools.

Also, consider using an RAII container such as vector instead of
explicitly using malloc and free (http://www.parashift.com/c++-faq-
lite/containers.html#faq-34.1), or at least use a smart pointer list
std::tr1::shared_ptr to automatically clean up.

Cheers! --M
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,989
Messages
2,570,207
Members
46,782
Latest member
ThomasGex

Latest Threads

Top