Search code examples
c#arraysgcallowverylargeobjects

gcAllowVeryLargeObjects is set but still causing System.ArgumentOutOfRangeException


I'm a little bit out of ideas. With the following code I try to instace a byte array > than 2GB:

var b = Array.CreateInstance(typeof(byte), uint.MaxValue);

Every time it will cause an System.ArgumentOutOfRangeException excpetion with the message that arrays larger then 2GB are not supported.

My App.config is currently the following:

<?xml version="1.0" encoding="utf-8" ?>
   <configuration>
      <startup> 
         <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2"/>
      </startup>
      <runtime>
         <gcAllowVeryLargeObjects enabled="true" />
      </runtime>
   </configuration>

Further the target platform of the project is x64

I'd be grateful for any ideas. Should there be any information missing I will update the question so as soon as possible.

Update 1

I also tried uint.MaxValue


Solution

  • Just for sanity check, you are trying to allocate 9.223 EB (exabytes) sequential block of memory and that is 9.223×10^9 GB (gigabytes). Simply, but you cannot even do that on x64 machine as some memory is used anyways and that would be maximum.

    Instead try to use dynamically growing list:

    var b = new List<byte>();
    

    edit:

    The maximum index in any single dimension is 2,147,483,591 (0x7FFFFFC7) for byte arrays and arrays of single-byte structures, and 2,146,435,071 (0X7FEFFFFF) for other types.' - source: https://learn.microsoft.com/en-us/dotnet/framework/configure-apps/file-schema/runtime/gcallowverylargeobjects-element

    The effect of gcallowverylargeobjects-element is that you can define multi-dimentsional arrays that exceed 2Gb and in case of other data types you can allocate 2146435071*data_type_size memory. For example int32 consists for 4 bytes, so it would be 8.586 GB (gigabytes).