这应该每秒用大约 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/