Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maximum length of byte[]?

Tags:

I'm trying to create an array of bytes whose length is UInt32.MaxValue. This array is essentially a small(ish) in-memory database:

byte[] countryCodes = new byte[UInt32.MaxValue]; 

On my machine, however, at run-time, I get a System.OverflowException with "Arithmetic operation resulted in an overflow".

What's the deal? Do I need to use an unsafe block and malloc? How would I do that in C#?

like image 464
GoHeavyOrGoHome Avatar asked Oct 15 '10 16:10

GoHeavyOrGoHome


2 Answers

The current implementation of System.Array uses Int32 for all its internal counters etc, so the theoretical maximum number of elements is Int32.MaxValue.

There's also a 2GB max-size-per-object limit imposed by the Microsoft CLR.

A good discussion and workaround here...

  • BigArray<T>, getting around the 2GB array size limit

And a few related, not-quite-duplicate, questions and answers here...

  • Is there a limit of elements that could be stored in a List ?
  • Very large collection in .Net causes out-of-memory exception
  • what is the max limit of data into list in c#?
like image 135
LukeH Avatar answered Sep 16 '22 14:09

LukeH


On .NET 4.5 The maximum instantiatable length of a byte array is: 2147483591, or 56 less than int.MaxValue. Found via:

for (int i = int.MaxValue; i > 0; i--) {     try     {         byte[] b = new byte[i];         Console.Out.WriteLine("MaxValue: " + i);         Environment.Exit(0);     }     catch (Exception ignored)     {} } 
like image 42
Nick Avatar answered Sep 20 '22 14:09

Nick