#include <iostream>
#include <string>
#include <deque>
#include <vector>
#include <unistd.h>
using namespace std;
struct Node
{
string str;
vector<string> vec;
Node(){};
~Node(){};
};
int main ()
{
deque<Node> deq;
for(int i = 0; i < 100; ++i)
{
Node tmp;
tmp.vec.resize(100000);
deq.push_back(tmp);
}
while(!deq.empty())
{
deq.pop_front();
}
{
deque<Node>().swap(deq);
}
cout<<"releas\n";
sleep(80000000);
return 0;
}
通过top
,我发现我的程序内存大约是61M,为什么?如果 Node
中有复制构造函数也没关系。我想知道为什么,而不是如何使其正确。
海湾合作委员会(海湾合作委员会)4.9.1,中心
最佳答案
一般new
/delete
和malloc
/realloc
/free
安排使用 sbrk()
从操作系统获得更多内存或特定于操作系统的等价物,并按照他们喜欢的方式划分页面以满足程序的分配请求。尝试将小页面释放回操作系统是不值得的 - 过多的额外开销跟踪页面是/不是池的一部分,重新请求它们等。在内存不足的情况下,正常的缓存机制将允许很长时间-无论如何都要将未使用的内存页面换出物理 RAM。
FWIW,GNU libC 的 malloc
等。对特别大的请求进行异常(exception)处理,以便在程序终止之前可以完全释放它们以供操作系统/其他程序使用;引自 the NOTES section here :
When allocating blocks of memory larger than
MMAP_THRESHOLD
bytes, the glibcmalloc()
implementation allocates the memory as a private anonymous mapping usingmmap
(2).MMAP_THRESHOLD
is 128 kB by default, but is adjustable usingmallopt
(3). Allocations performed usingmmap
(2) are unaffected by theRLIMIT_DATA
resource limit (seegetrlimit
(2)).
关于c++ - 为什么我的程序内存不释放?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29529135/