What's in the memory of a dynamic array when used with SetLength in Delphi? What's in the memory of a dynamic array when used with SetLength in Delphi? arrays arrays

What's in the memory of a dynamic array when used with SetLength in Delphi?


Quoted from the Delphi 7 help, "For a long-string or dynamic-array variable, SetLength reallocates the string or array referenced by S to the given length. Existing characters inthe string or elements in the array are preserved, but the content of newly allocated space is undefined. The one exception is when increasing the length of a dynamic array in which the elements are types that must be initialized (strings, Variants, Variant arrays, or records that contain such types). When S is a dynamic array of types that must be initialized, newly allocated space is set to 0 or nil."

From my observation, for static array, uninitialized elements contain random data. For dynamic array, AFAIK since Delphi 7, uninitialized elements contain their default nothing value. However, you shouldn't rely on this fact because it was implementation detail of SetLength. You should follow the official documentation instead.


In practice, it is initialized with zero's.

The method SetLength internally calls System.DynArraySetLength.
Using Delphi 5, the memory gets filled with #0.

// Set the new memory to all zero bitsFillChar((PChar(p) + elSize * oldLength)^, elSize * (newLength - oldLength), 0);

I assume this behavior has not changed in more recent versions of Delphi.