一个程序可以分配多少内存?

use*_*635 5 c++ linux out-of-memory

我可以为 Linux 下运行的 C++ 程序分配多少内存?在我的测试用例中,使用newormalloc可以分配超过 170Gb 的内存。作为比较,同样的代码在windows中只能分配1.8G然后终止。

我的测试机,一台是使用virtual box的虚拟机,centos7 64位,2Gb内存。主机是win10 64位,内存8Gb。

使用 free 命令的屏幕截图, 在此输入图像描述

下面是测试代码,

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

 #define EVERY_ALLOC_MEM 1024 * 1014 // 1Mb
int main(int argc, char *argv[])
{
    std::cout << getpid() << ":" << argv[0] << std::endl;
    for (size_t i = 0; ; i++)
    {
        //char* mem = new char[EVERY_ALLOC_MEM];
        char* mem = (char*)malloc(EVERY_ALLOC_MEM);
        std::cout << "used " << i  << "Mb, that is " << i * 1024 << "Kb, and " << (float)i/1024 << "Gb"<< std::endl;       
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

use*_*635 0

这确实是Linux的内存优化技术。如果您尝试写入分配的内存,例如memset(mem, 0, EVERY_ALLOC_MEM),它将会被暴露。这与页面错误有关。