c++ - new 不分配内存

标签 c++ memory

这应该每秒用大约 100 MB 填满我的内存。我使用 gnome-systemmonitor 和 htop 跟踪内存使用情况。但不知何故它没有。为什么?

#include "unistd.h"
#include <iostream>

int main(int argc, char *argv[])
{
    while (true){
        std::cout << "New one" << std::endl;
        new char[100000000];
        sleep(1);
    }
    return 0;
}

运行:

g++ -std=c++11 -O0  main.cpp; ./a.out  

最佳答案

因为您没有使用它,所以 Linux 会进行惰性分配,因此在您使用它之前它不会实际映射任何内存页。

如果你输入一些代码:

char* test = new char[100000000];
test[0] = 'a';
test[4096] = 'b';
...

您应该看到它实际上正在消耗您的系统内存。

关于c++ - new 不分配内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29944433/

相关文章:

.net - 如何在客户端计算机上安装 Microsoft.VisualStudio.Shell.dll

c++ - 如何索引到 C++ shared_ptr/unique_ptr 数组?

c++ - 地址是什么数据类型?

c - 如何知道 C 函数 free 是否正常工作?

C++ 视口(viewport)缓存目录中的文件

javascript - Chrome 中的 CreateObjectURL 内存泄漏

c++ - 在循环中声明变量是否有任何开销? (C++)

c++ - 我如何获得一个模板来支持 T* 而不是 T&?

ios - 数组只是不断添加对象和内存崩溃

swift - 如何从内存中清除 SKSpriteNode?