OutOfMemoryException when allocation large memory blocks
Dear Softwaredevelopers,
In my application I have to allocate a huge amount of memory but the following C# console programm creates an OutOfMemoryException when I try to allocate memory >512 MB. and I wonder why.
My System:
Intel Core2 Quad CPU 3GB
Windows XP 32-Bit
Visual Studio 2008
available free memory 2.3GB
Can anybody help?
Greetings Christian
using System;
using System.Collections.Generic;
using System.Text;
namespace MemoryAllocation
{
class Program
{
static void Main(string[] args)
{
int size = 2;
while (size > 0)
{
Byte[] b = new Byte[size];
for (int i = 0; i<size; ++i)
b[i] = 13;
size *= 2;
}
Re: OutOfMemoryException when allocation large memory blocks
the execption occurs when I have 2.3 GB free space and want to allocate more than 512MB...
in the while loop I only wanted to find out what the limit is.
It also occurs withot the while loop.
the memory will be and is cleaned by the garbage collector.
Re: OutOfMemoryException when allocation large memory blocks
As Arjay said, you have no terminating condition in your while loop; 'size' is always greater than 0 because you never decrease it (you actually add to it).
Re: OutOfMemoryException when allocation large memory blocks
Originally Posted by guentherc
the execption occurs when I have 2.3 GB free space and want to allocate more than 512MB...
in the while loop I only wanted to find out what the limit is.
It also occurs withot the while loop.
the memory will be and is cleaned by the garbage collector.
You might think so, but in this type of tight loop, you'll run out of memory before the cg has a chance to run. Or, even if the cg has a chance to run, it won't be able to keep up.
Re: OutOfMemoryException when allocation large memory blocks
Or it's possible that your operating system does not have 512MB of contiguous free RAM and therefore cannot fulfill your request. Every programming language will hit the exact same issue, though the exact point at which they hit it will vary depending on what your operating system is doing.
It's very unusal for an application to actually require such large memory buffers. Generally you can use a chunked approach and process 4MB at a time (or less) which can result in a more performant application. Have you considered that approach?
NOTE: My code snippets are just snippets. They demonstrate an idea which can be adapted by you to solve your problem. They are not 100% complete and fully functional solutions equipped with error handling.
* The Best Reasons to Target Windows 8
Learn some of the best reasons why you should seriously consider bringing your Android mobile development expertise to bear on the Windows 8 platform.