【问题标题】:How much memory a program can allocate?一个程序可以分配多少内存?
【发布时间】:2019-08-01 03:21:06
【问题描述】:

我可以为在 Linux 下运行的 C++ 程序分配多少内存?在我的测试用例中,使用new 或malloc 可以分配超过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;
}

【问题讨论】:

  • 您看到的是 Linux 的乐观内存分配行为:stackoverflow.com/questions/28267364/…
  • 我测试了'cat /proc/sys/vm/overcommit_memory',结果为零,这意味着当用户空间请求更多内存时,内核会评估当前的空闲内存量,如果是够了,可以分配,还是失败。所以还是一头雾水。

标签: c++ linux out-of-memory


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2011-08-27
    • 1970-01-01
    • 2014-03-02
    • 2020-03-12
    • 2014-01-31
    • 2011-07-27
    • 1970-01-01
    • 2015-05-01
    • 1970-01-01
    相关资源
    最近更新 更多