为什么我的程序的内存没有释放? [英] Why does my program's memory not release?

查看:264
本文介绍了为什么我的程序的内存没有释放?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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中有一个复制构造函数也可以.我想知道为什么,而不是如何使其正确.

By top ,I found my program's memory was about 61M, why? And it's ok if there is a copy-constructor in Node.I would like to know why , not how to make it correct.

gcc(GCC)4.9.1,厘托

gcc (GCC) 4.9.1, centos

推荐答案

通常,new/deletemalloc/realloc/free使用

Generally, new/delete and malloc/realloc/free arrange for more memory from the OS using sbrk() or OS-specific-equivalent, and divide the pages up however they like to satisfy the program's allocation requests. It's not worth the bother to try to release small pages back to the OS - too much extra overhead tracking the pages that are / are not still part of the pool, rerequesting them etc.. In low memory situations, normal caching mechanisms will allow long-unused memory pages to be swapped out of physical RAM anyway.

FWIW,GNU libC的malloc等.对特别大的请求进行例外处理,以便可以在程序终止之前将其完全释放给OS/其他程序使用;引用此处的NOTES部分:

FWIW, GNU libC's malloc et al. makes an exception for particularly large requests so they can be fully released for the OS / other programs to use before program termination; quoting from the NOTES section here:

分配大于MMAP_THRESHOLD个字节的内存块时,glibc malloc() 实现将内存分配为私有匿名映射 使用mmap(2). MMAP_THRESHOLD默认为128 kB,但 可使用mallopt(3)进行调整.使用mmap(2)执行的分配是 不受RLIMIT_DATA资源限制的影响(请参见getrlimit(2)).

When allocating blocks of memory larger than MMAP_THRESHOLD bytes, the glibc malloc() implementation allocates the memory as a private anonymous mapping using mmap(2). MMAP_THRESHOLD is 128 kB by default, but is adjustable using mallopt(3). Allocations performed using mmap(2) are unaffected by the RLIMIT_DATA resource limit (see getrlimit(2)).

这篇关于为什么我的程序的内存没有释放?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆