Maximum length of a dynamic array in Delphi?

I was curious how long a dynamic array could be, so I tried

SetLength(dynArray, High(Int64));

This has a value of 9,223,372,036,854,775,807, and I believe that this will be the largest number of indexes that I could reference in any case. This gave me:

ERangeError with the message "Range check error".

So I tried:

SetLength(dynArray, MaxInt); 

and got the same error!

I wonder what I could call him

SetLength(dynArray, Trunc(Power(2, 32));

Which is actually twice as much as MaxInt!

I tried

SetLength(dynArray, Trunc(Power(2, 63) - 1));

Same as High (Int64), and that didn't work either.

Except for continuing trial and error, does anyone know the maximum size? Does it depend on the size of the elements in the array?

I am using Delphi 2009. Will it be different for different versions (obviously, when Commadore comes out, it should be bigger!)

+3
4

System.DynArraySetLength 20628:

Inc(neededSize, Sizeof(Longint)*2);
if neededSize < 0 then
  Error(reRangeError);

, , Maxint - SizeOf (Longint) * 2. , .

+17

, .

, , , . Windows (32 , , , Delphi ), 2 3 . , Delphi 3- , , LongWords .

, , , 80% 90% MaxInt div SizeOf(array element) - , .

: int64 , . :

procedure TForm1.Button1Click(Sender: TObject);
var
  a: array of byte;
  l: int64;
begin
  l := $4000000000;
  SetLength(a, l);
  Caption := IntToStr(Length(a));
end;

, . , 0 SetLength(). SetLength(), , , .

+4

Please note that the element afaik elementcount is also limited, more than 2 ^ 31-1 is unlikely. Perhaps this size has the same limit (to avoid signed <> unsigned problems in RTL). I doubt that more than 2 GB is possible even in / 3GB mode.

+1
source

MMaths:

max_array_bytesize = 2 ^ 31 - 9

max_array_elements_number = [(2 ^ 31 - 9) / array_element_bytesize]

code:

max_array_elements_number := (MaxInt-Sizeof(Longint)*2) div SizeOf(array_element);

Example:

type
  TFoo = <type_description>;
  TFooDynArray = array of TFoo
const
  cMaxMemBuffSize = MaxInt-Sizeof(Longint)*2;
var
  A : TFooDynArray;
  B : array of int64;
  MaxElems_A : integer;
  MaxElems_B : integer;
begin
  MaxElems_A := cMaxMemBuffSize div SizeOf(TFoo);
  MaxElems_B := cMaxMemBuffSize div SizeOf(int64);

  ShowMessage('Max elements number for array:'#13#10+
              '1) A is '+IntToStr(MaxElems_A)+#13#10+
              '2) B is '+IntToStr(MaxElems_B)
              );
end;
+1
source

Source: https://habr.com/ru/post/1710312/


All Articles