0

We have code like this:

  void main(){
  std::list<int *> ll;
  for(int i=0;i<100;i++)
   {
      int *a = new int[10000];
      ll.push_back(a);
   }
  for(int *b : ll)
  {
     delete [] b;
  }  
 ll.clear();

}

But the memory not free? Why? When run this code work correctly:

void main(){
 for(int i=0;i<100;i++)
 {
     int *a = new int[10000];
     delete [] a;
 }
}

I monitor memory with top command in linux and system monitoring, so in first code in first for the memory was going up and after that i expect that in last for the app free the memory but not free memory.

2 Answers2

4

[I monitor memory] in linux with top command and system monitoring

This approach will not give you an accurate result. Linux top command tells you how much memory the process holds, which includes the memory the allocator requested from OS. top does not know how much of this memory has been given to your program by the allocator, and how much is kept for giving to your program in the future.

In order to check your program for memory leaks and other memory-related errors use a memory profiling tool, such as valgrind. The profiler would detect memory leaks, and inform you of the places in your program that allocated blocks of memory which were not returned back to the allocator.

Note: The reason your other code appears to work is that the allocator needs a lot less memory, because the same chunk of memory gets allocated and de-allocated repeatedly in the loop.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
3

Like others said valgrind is the appropriate tool to use when tracking down memory leaks. Using valgrind on your program indeed shows that you have no memory leak:

    $ valgrind --leak-check=yes ./example 
==3945== Memcheck, a memory error detector
==3945== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==3945== Using Valgrind-3.10.1 and LibVEX; rerun with -h for copyright info
==3945== Command: ./example
==3945== 
==3945== 
==3945== HEAP SUMMARY:
==3945==     in use at exit: 0 bytes in 0 blocks
==3945==   total heap usage: 200 allocs, 200 frees, 4,002,400 bytes allocated
==3945== 
==3945== All heap blocks were freed -- no leaks are possible
==3945== 
==3945== For counts of detected and suppressed errors, rerun with: -v
==3945== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
scott-eddy
  • 128
  • 1
  • 5