Consider the code below which compiles and runs without error in Delphi 6. When I recover the dynamic string array, instead of seeing an empty array in sa, I see an array with a length of 1 with a single element containing an empty string. Why is this and how can I safely assign a NIL dynamic array to a Variant and recover it properly? Here’s the code:
TDynamicStringArray = array of string;
var
V: Variant;
sa: TDynamicStringArray;
begin
sa := nil;
V := sa;
sa := V;
OutputDebugString('sa has a single element now with an empty string in it when I expect it to be empty.');
end;
There are two bugs here.
First of all in
Variants.DynArrayVariantBounds. When the dynamic array isnilthis erroneously returns a low/high bounds pair of(0, 0). It should return(0, -1). This bug is fixed in the latest versions of Delphi. That causesV := sato return a variant array with a single, empty, element.The second bug affects the other direction,
sa := V. This bug is still present in the latest versions of Delphi. This bug is inVariants.DynArrayFromVariant. There is arepeat/untilloop which walks over the input variant array and populates the output dynamic array. When the input variant array is empty, it should not enter thatrepeat/untilloop. However, the code erroneously does so and attempts to read an element of the variant array withVarArrayGet. Since the array is empty, that provokes a runtime error. I have reported this: QC#109445.Here is a very simply bit of code that fixes the bugs. Note that I have only consider the case where the arrays are one dimensional. If you need to support higher dimensional arrays then you can extend this approach to do so.