Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
like image 863
seveleven Avatar asked Oct 21 '10 06:10

seveleven


1 Answers

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.

like image 61
Vantomex Avatar answered Oct 13 '22 02:10

Vantomex