[英]Memory leak c++ list of array
我們有這樣的代碼:
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命令監視內存,因此在第一個代碼中首先顯示該內存,然后在此之后,我希望該應用最后釋放內存但不釋放內存。
在Linux中使用頂級命令和系統監視來監視內存
這種方法不會給您准確的結果。 Linux top
命令告訴您該進程擁有多少內存,其中包括分配器從OS請求的內存。 top
不知道分配器已將多少內存分配給您的程序,以及將來會為您的程序保留多少內存。
為了檢查程序是否存在內存泄漏和其他與內存相關的錯誤,請使用內存分析工具,例如valgrind 。 探查器將檢測內存泄漏,並通知您程序中已分配內存塊的位置,這些內存塊並未返回給分配器。
注意:您其他代碼似乎起作用的原因是分配器需要的內存要少得多,因為在循環中重復分配和取消分配了相同的內存塊。
與其他人一樣, valgrind是跟蹤內存泄漏時使用的適當工具。 在程序上使用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.