Home > Back-end >  In Delphi should I free "array of array of" variables?
In Delphi should I free "array of array of" variables?

Time:09-28

Say I have a class field

a : array of array of double;

it is allocated using nested SetLength calls.

SetLength(a,100);
for i := 0 to length(a)-1 do SetLength( a[i], 100 );

On object Destroy is it necessary to loop through the first level of array to free the second level items of it?

for i := 0 to length(a)-1 do a[i] := NIL;

Is it necessary or the compiler handles freeing of multi dimensional dynamic arrays too?

CodePudding user response:

Dynamic arrays are managed by the compiler. When a dynamic array's reference count drops to zero, it is automatically freed.

This is equally true for multidimensional dynamic arrays of any dimension, at every level.

So when your field a goes out of scope, this dynamic array's reference count is reduced by one. If the new reference count is zero, the array is freed, and so the reference counts of all elements a[0], a[1], ..., a[High(a)] are reduced by one. And, again, if they reach zero, they are freed too.

You don't need to do anything.

CodePudding user response:

You can set the size of a multi-dimensional dynamic array with a single SetLength() call. No need to use any loop.

You do this by simply calling SetLength(DynamicArray, FirstDimensionSize, SecondDimensionSize, ..NthDimensionSize).

So, in your case, you could set the initial size of your dynamic array by simply using:

SetLength(a,100,100);

And then when freeing up the array, you just call:

SetLength(a,0,0);
  • Related