Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory allocation - How 15 GB can be equal to 2GB?

A major application of mine, is crashing at run time.

I want to find out if this is related to a memory allocation issue by the system. Thus, I created a small test program to allocate 1GB of memory and simultaneously ran 15 such processes, thus using 15GB of RAM in total.

However, when I run this program the task manager shows that it has occupied only 2GB of RAM? How is that possible?

I wrote a sample code as follows

char *ptr[1024];
for ( i = 0 ; i < 1024 ; ++i )
{
    ptr[i] = new char[1024 * 1024];
    std::cout << " Allocated 1024 MB" << i << " th time " << std::endl;
}
like image 719
nsivakr Avatar asked Nov 29 '22 15:11

nsivakr


1 Answers

Windows is a demand-paged virtual memory operating system. Allocating memory with operator new only allocates virtual memory. You won't start using physical memory, RAM, until you actually access the memory. Which you did not do.

You can force the RAM to be allocated by touching every 4096th byte, better make that a write or it will be optimized away:

    size_t size = 1024 * 1024;
    ptr[i] = new char[size];
    for (size_t j = 0; j < size; j += 4096) ptr[i][j] = 0;

But that's quite a pointless thing to do, it just slows your program down. And doesn't actually test anything, a process cannot run out of RAM on Windows. Put Task Manager into programmer mode, add the column for Commit size. That's the real number.

like image 92
Hans Passant Avatar answered Dec 06 '22 20:12

Hans Passant