Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when increasing the size of a dynamic array?

Tags:

delphi

I'd like to understand what happens when the size of a dynamic array is increased.

My understanding so far:

  • Existing array elements will remain unchanged.
  • New array elements are initialised to 0
  • All array elements are contiguous in memory.

When the array size is increased, will the extra memory be tacked onto the existing memory block, or will the existing elements be copied to a entirely new memory block?

Does changing the size of a dynamic array have consequences for pointers referencing existing array elements?

Thanks,

[edit] Incorrect assumption struck out. (New array elements are initialised to 0)

like image 635
Shannon Matthews Avatar asked Feb 04 '23 00:02

Shannon Matthews


1 Answers

  • Existing array elements will remain unchanged: yes
  • New array elements are initialized to 0: yes (see update) no, unless it is an array of compiler managed types such as string, an other array or a variant
  • All array elements are contiguous in memory: yes

When the array size is increased, the array will be copied. From the doc: ...memory for a dynamic array is reallocated when you assign a value to the array or pass it to the SetLength procedure.

So yes, increasing the size of a dynamic array does have consequences for pointers referencing existing array elements.

If you want to keep references to existing elements, use their index in the array (0-based).

Update

Comments by Rob and David prompted me to check the initialization of dynamic arrays in Delphi5 (as I have that readily available anyway). First using some code to create various types of dynamic arrays and inspecting them in the debugger. They were all properly initialized, but that could still have been a result prior initialization of the memory location where they were allocated. So checked the RTL. It turns out D5 already has the FillChar statement in the DynArraySetLength method that Rob pointed to:

  // Set the new memory to all zero bits
  FillChar((PChar(p) + elSize * oldLength)^, elSize * (newLength - oldLength), 0);
like image 139
Marjan Venema Avatar answered Feb 12 '23 01:02

Marjan Venema