STL不会从系统级别释放内存 [英] STL not release memory from System level

查看:103
本文介绍了STL不会从系统级别释放内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,STL具有自动内存管理功能.但是,当我使用topps -aux之类的东西来显示进程的内存使用情况时,它表明即使STL对象也超出范围,这些内存仍由进程拥有.

As I know STL has automatic memory management. But when I use something like top or ps -aux to show the memory usage of a process, it shows even the STL object are out of scope, these memory is still possessed by process.

这里是一个例子:

void run()
{
    map<int, int> a;
    for(int i = 0; i < 1000000; i++)
    { 
        a[i] =  i;
    } // 64376K memory used by process
}

int main()
{
    run();
    sleep(5); // still 64376 memory used
    map<int, int> a;
    for(int i = 0; i < 1000000; i++)
    { 
        a[i] =  i;
    } // still 64376 memory used
    return 0;
}

该进程在run()中具有64376KB的内存,并且在功能run()之后不释放内存.但是这些内存似乎被第二个map使用.

The process possesses 64376KB memory in run() and memory doesn't release after function run(). But these memory seems to be used by the second map.

使用valgrind --tool=massif检查发生了什么之后,我得到了正常结果.

After I use valgrind --tool=massif to check what happened, I got a normal result.

所以我的问题来了

  1. 为什么进程内存趋势与代码和valgrind
  2. 不匹配
  3. 不同的STL对象如何共享相同的已分配内存.
  1. why process memory trends doesn't match with the code and valgrind
  2. How does the different STL objects share the same allocated memory.

推荐答案

这是完全正常的.这就是操作系统的工作方式.如果他们花费所有时间从微小的进程中回收微小的内存部分,那么他们将永远别无所求.

This is completely normal. That's how operating systems work. If they spent all their time reclaiming tiny portions of memory from tiny processes, they'd never do anything else.

您只需要相信他们复杂的算法知道他们正在做什么才能为您的系统获得最佳性能.

You just have to trust that their complicated algorithms know what they're doing to get the best performance for your system.

在逻辑层的每一层上都有一层,这些层一直分配物理RAM直到进程的虚拟内存.

There are layers on layers on layers of logic that allocate physical RAM all the way up to the process's virtual memory.

关于操作系统如何工作的极端细节既不在本文讨论范围之内,也毫无意义.但是,如果您真的想掌握所有相关知识,则可以参加相关的教学课程.

Going into extreme detail about how operating systems work would be both beyond the scope of this post, and pointless. However, you could enrol on a relevant teaching course if you really wanted to grok it all.

如果我们忘记了缓存和虚拟内存之类的东西,那么即使是一个简单的经验法则也可以总结如下:从程序中释放内存告诉操作系统它可以将其取回.这并不意味着操作系统必须将其收回.

If we were to forget about caching and virtual memory and such, even a simple rule of thumb might be summarised as follows: releasing memory from your program tells the OS it can have it back; that doesn't mean the OS must take it back.

这篇关于STL不会从系统级别释放内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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