Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is SetLength() allocating memory in Delphi

Tags:

delphi

When an array is declared in this form, the memory is allocated statically:

var
  Data: array[0..5] of integer;

My question is when the array is declared in the following way:

var
  Data: array of integer;
....
SetLength( Data, Length( Data ) + 1 );

Is the memory allocated statically or dynamically?

I think that the memory is allocated statically and the array is copied in memory, but I am not certain.

like image 590
Johni Douglas Marangon Avatar asked Mar 21 '23 18:03

Johni Douglas Marangon


1 Answers

This is dynamic allocation, for three reasons:

  1. Static allocation can only happen at compile-time. As a general rule, if you're using a procedure or function to do it, it's dynamic memory being allocated from the memory manager.
  2. Since the value of Length( Data ) + 1 depends on information that's only known at runtime, it can't be allocated statically.
  3. Static literally means "unchanging," and dynamic means "changing." Your SetLength call is changing the size of the array, increasing it by 1. Therefore, it can only be dynamic allocation at work here.
like image 105
Mason Wheeler Avatar answered Mar 27 '23 17:03

Mason Wheeler