简体   繁体   English

数组的内存泄漏C ++列表

[英]Memory leak c++ list of array

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. 我在linux和系统监视中使用top命令监视内存,因此在第一个代码中首先显示该内存,然后在此之后,我希望该应用最后释放内存但不释放内存。

[I monitor memory] in linux with top command and system monitoring 在Linux中使用顶级命令和系统监视来监视内存

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. Linux top命令告诉您该进程拥有多少内存,其中包括分配器从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. top不知道分配器已将多少内存分配给您的程序,以及将来会为您的程序保留多少内存。

In order to check your program for memory leaks and other memory-related errors use a memory profiling tool, such as valgrind . 为了检查程序是否存在内存泄漏和其他与内存相关的错误,请使用内存分析工具,例如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. 注意:您其他代码似乎起作用的原因是分配器需要的内存要少得多,因为在循环中重复分配和取消分配了相同的内存块。

Like others said valgrind is the appropriate tool to use when tracking down memory leaks. 与其他人一样, valgrind是跟踪内存泄漏时使用的适当工具。 Using valgrind on your program indeed shows that you have no memory leak: 在程序上使用valgrind确实表明您没有内存泄漏:

    $ 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM