Skip to content
Advertisement

How much memory a program can allocate?

How much memory can I allocate for a C++ program running under Linux? In my test case, using new or malloc can allocate more than 170Gb of memory. As a comparison, The same code can only allocate 1.8G in windows and then terminated.

My test machine, one is a virtual machine using virtual box, centos7 64-bit, 2Gb memory. The host is win10 64-bit, memory 8Gb.

Screenshot of using the free command, enter image description here

Below is the test code,

#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;
}

Advertisement

Answer

This is indeed Linux’s memory optimization technology. If you try to write to the allocated memory, such as memset(mem, 0, EVERY_ALLOC_MEM), it will be revealed. This is related to page fault.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement