首页 > 解决方案 > 为什么删除和清除所有对象后内存没有返回系统?

问题描述

#include <chrono>
#include <cstdio>
#include <list>
#include <thread>

struct a {
  char data[1024];
};

struct b {
  char data[1024];
};

struct c {
  char data[1024];
};

struct d {
  char data[1024];
};

int main() {
  std::list<a *> a_list;
  for (size_t i = 0; i < 1000000; i++) {
    a_list.push_back(new a);
  }

  std::list<b *> b_list;
  for (size_t i = 0; i < 1000000; i++) {
    b_list.push_back(new b);
  }

  std::list<c *> c_list;
  for (size_t i = 0; i < 1000000; i++) {
    c_list.push_back(new c);
  }

  std::list<d *> d_list;
  for (size_t i = 0; i < 1000000; i++) {
    d_list.push_back(new d);
  }

  printf("---\n"); // line A
  while (a_list.size() > 0) {
    a *item = a_list.front();
    a_list.pop_front();
    delete item;
  }

  printf("---\n");
  while (b_list.size() > 0) {
    b *item = b_list.front();
    b_list.pop_front();
    delete item;
  }

  printf("---\n");
  while (c_list.size() > 0) {
    c *item = c_list.front();
    c_list.pop_front();
    delete item;
  }

  printf("---\n");
  while (d_list.size() > 0) {
    d *item = d_list.front();
    d_list.pop_front();
    delete item;
  }

  printf("end\n"); // inline B

  std::this_thread::sleep_for(std::chrono::hours(1));
}

在 A 行,进程内存使用率为 26%。在 B 行,进程内存使用率为 26%!

为什么会这样?

更多案例:

  1. 当我删除b,cdand just leavea时,结果是一样的。
    如果我将a数组的长度设置为130000,结果是一样的,但是当我将它增加到 140000 时,结果就不同了:内存实际上被释放了。

  2. 在空闲行之后,我添加了更多代码以使用 为更多项目分配更多内存new,然后内存使用量上升,但分配的字节数比第一次少。

标签: c++memory-leaks

解决方案


注意:这不是我的答案,我是从 MX 的评论中引用的。Andrieux“不需要一个进程将释放的内存返回给操作系统,它可以保留它以便以后更快地分配。”

我确信该程序将在关闭程序后返回所述内存。尽管程序创建的任何文件在关闭程序后都将保留在磁盘内存中。


推荐阅读