I have a dynamic array myArr
. What is stored in the memory in myArr
when we use SetLength
on it? Is it '00'? Or undefined?
SetLength
allocates 16 bytes of memory for myArr
in this case.
myArr : array of byte;
SetLength(myArr, 16);
I have a dynamic array myArr
. What is stored in the memory in myArr
when we use SetLength
on it? Is it '00'? Or undefined?
SetLength
allocates 16 bytes of memory for myArr
in this case.
myArr : array of byte;
SetLength(myArr, 16);
It is initialized to 0
SetLength
internally calls System.DynArraySetLength
.
Using Delphi 5, the memory is filled with #0.
// Set the new memory to all zero bits
FillChar((PChar(p) + elSize * oldLength)^, elSize * (newLength - oldLength), 0);
I assume this behavior has not changed in more recent versions of 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 in
the 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.