在C++中实际为newint[250000000]分配内存时?
我试图弄清楚什么时候为我的程序分配了内存。这是我的代码
#include <unistd.h>
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
cout << "when the memory is allocated?";
cout << endl;
cout.flush();
int * p = new int[250000000];
sleep(3);
cout << "address: " << p;
cout << endl;
cout.flush();
sleep(3);
cout << "value" << p[0];
cout << endl;
cout.flush();
sleep(10);
cout << "ending";
cout << endl;
return 0;
}
我用 mac 上的活动监视器跟踪它。
我发现我没有得到我申请的 GB 内存。什么时候new int[250000000]在 C++ 中实际分配内存?
回答
OSX 与其他 Unix 操作系统一样,虚拟内存和实际使用的内存之间存在差异。在控制台程序中,top它们被称为 VIRT 和 RES(用于驻留)。
当您分配这样的大块时,程序会调用操作系统来保留虚拟内存空间。该内存只会在您的程序写入时实际使用。不是当它从中读取时,因为虚拟页面将全部映射为零开始。
因此,要查看实际使用的内存,请编写一个循环将每个数组条目设置为某个数字。
这是你的程序的 C++17 更新版本(如果你在阅读之前因为某种原因再次阅读它,我的粘贴缓冲区中有旧版本):
#include <chrono>
#include <iostream>
#include <thread>
using namespace std;
using namespace std::literals;
int main() {
cout << "when the memory is allocated?";
cout << endl;
constexpr size_t p_count = 250000000;
int *p = new int[p_count];
this_thread::sleep_for(3s);
cout << "address: " << p;
cout << endl;
this_thread::sleep_for(3s);
cout << "value: " << p[0];
cout << endl;
for (size_t i = 0; i < p_count; ++i) {
p[i] = i;
}
this_thread::sleep_for(10s);
cout << "ending";
cout << endl;
return 0;
}