Paul Michaels
Paul Michaels

Reputation: 16705

Unable to use up spare memory

I have the following console application, which has the sole purpose of using all the spare memory on the running machine:

static List<string> _str = new List<string>();
static int fill = 10000;
static int _remainingMemory = 50;

static void Main(string[] args)
{
    fillString();

    Console.ReadLine();
}

static void fillString()
{
    long count = 0;
    while (true)
    {
        try
        {
            if (++count % 500 == 0 || fill == 1)
            {
                ShowMemory();
            }

            _str.Add(new string('_', fill));
        }
        catch (OutOfMemoryException)
        {
            if (fill > 1)
            {                                         
                fill = 1;
            }
            else
            {
                Console.WriteLine("Not consuming memory...");
                return;
            }
        }
    }
}

private static void ShowMemory()
{
    System.Diagnostics.PerformanceCounter ramCounter;

    ramCounter = new System.Diagnostics.PerformanceCounter("Memory", "Available MBytes");
    Console.WriteLine("Memory Remaining: {0}", ramCounter.RawValue);
}

What this does is use up about 1GB of memory, but leaves nearly 10GB free. So, my question is, why does this code not use up every last byte of memory on the machine and bring it to a standstill?

I'm using VS2015 under Windows 8.1.

Upvotes: 0

Views: 59

Answers (2)

Brian Rasmussen
Brian Rasmussen

Reputation: 116471

You application doesn't use memory directly. It uses virtual memory. The OS maps this to memory pages. Don't think about memory. Think about address space by default as that is the abstraction available to your app.

If your app is 32 bit, it is limited to 2 GB virtual memory by default. If it is large address aware it can access 3 or 4 GB on 32 bit Windows/64 bit Windows respectively.

If your app is 64 bit the available address space is 8 TB. This will most likely be limited by your OS's ability to back that with pages though (at least for a while anyway).

Upvotes: 1

oppassum
oppassum

Reputation: 1775

Windows sets a per-process limit on memory. Virtual Address space is limited to 2GB for your application, unless you specify certain flags in windows to override this.

Upvotes: 1

Related Questions