4

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.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • A rule of thumb: when size of an array variable known at compile time, that array said to be **static array** (and it reside), and when at run time - **dynamic array**. Dynamic array resides in heap. – Free Consulting Jan 31 '14 at 21:26

2 Answers2

5

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.
Mason Wheeler
  • 82,511
  • 50
  • 270
  • 477
2

The type that you declared, array of Integer, is known as a dynamic array. A dynamic array is allocated by calling SetLength and the memory is dynamic.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490