我们有这样的代码:
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();
}但是记忆不自由?为什么?当运行此代码时,正确工作:
void main(){
for(int i=0;i<100;i++)
{
int *a = new int[10000];
delete [] a;
}
}我使用linux中的top命令和系统监视来监视内存,所以在第一段代码中,内存是上升的,然后我希望应用程序释放内存,而不是释放内存。
发布于 2017-11-14 12:37:36
就像其他人说的那样,缬磨是追踪内存泄漏的合适工具。在您的程序中使用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)发布于 2017-11-14 12:27:07
我使用顶级命令和系统监视来监视linux中的内存。
这种方法不会给你一个准确的结果。Linux top命令告诉您进程拥有多少内存,其中包括分配程序从操作系统请求的内存。top不知道这个内存中有多少是由分配器分配给你的程序的,还有多少是将来留给你的程序的。
为了检查程序中的内存泄漏和其他与内存相关的错误,请使用内存分析工具(如缬磨 )。分析器将检测内存泄漏,并通知程序中分配未返回给分配器的内存块的位置。
注释:其他代码出现工作的原因是分配程序需要的内存要少得多,因为相同的内存块在循环中被分配和取消分配。
https://stackoverflow.com/questions/47285605
复制相似问题