Dynamic variables are variables allocated on the heap (also known as free store). The heap is the main portion of memory excluding the stack. The size of the heap is limited only by the amount of the computer's virtual memory (physical memory plus swap file).
Dynamic variables are allocated with the New procedure, which accepts a single pointer parameter. The New procedure allocates the appropriate amount of memory to store the value and assigns the address of the allocated memory block to the passed pointer. When you allocate memory for the pointer, the pointer doesn't reference another variable but has its own memory:
var P: PInteger; begin New(P); { create a dynamic integer } end.
Unlike static variables, dynamic variables aren't automatically managed. This means that you have to manually release the memory allocated for them. To release the memory allocated with the New procedure, use the Dispose procedure. If you forget to call the Dispose procedure to remove the dynamic variable from memory, your code will leak memory. Memory leaks diminish the performance of the application and may even cause it to crash.
You should always delete dynamic variables when you don't need them anymore:
var P: PInteger; begin New(P); { create a dynamic integer } { use the dynamic variable } P^ := 2005; WriteLn(P^); Dispose(P); { release the memory } ReadLn; end.
Strings and dynamic arrays are dynamic types allocated on the heap, but Delphi automatically manages their memory. To allocate memory for a dynamic array, use the SetLength procedure. To release the memory used by the array, you can either call the Finalize procedure or assign the nil value to the array.
var DynArray: array of Integer; begin SetLength(DynArray, 1000); { resize the array } Finalize(DynArray); { one way of releasing array memory } DynArray := nil; { another way of releasing array memory } end.
When you work with a string variable, memory is allocated when you assign text to the variable. You can also use the SetLength procedure to explicitly set the length of a string variable. To release the memory occupied by the string, assign a null string to the string variable.
var s: string; begin s := 'Dynamic allocation'; { release memory } s := ''; end.