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

标签 c++ linux out-of-memory

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

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

使用free命令的截图, enter image description here

下面是测试代码,

#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的内存优化技术。如果您尝试写入已分配的内存,例如 memset(mem, 0, EVERY_ALLOC_MEM),它将被泄露。这与页面错误有关。

关于c++ - 一个程序可以分配多少内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57301396/

相关文章:

linux - 如何将 base64 编码的 torrent info_hash 转换为磁力链接 info_hash? (Linux)

Docker在构建时被系统杀死

c++ - FFTW - 计算真正的 2D FFT,特殊要求

c++ - 从 800x600 中提取 800 和 600

c++ - 如何有效地按值(value)订购 map ?

java - 如何处理不断更新的大图像

linux - 生成报告时通过 jenkins Out of Memory 错误运行 Jmeter 脚本

c++ - C++如何读取特定的第一个字符并保存数据

编译我自己的内核(不是来自 linux-kernel 源代码)

linux - 为什么这会产生段错误?它应该只是退出