Указатель на вариантный тип

Материал из DRKB

Указатель на вариантный тип[править | править код]

I just ran across this in some of my old code and thought Id share it with you:

Consider the following (simplified code):


 function CreateVariantPtr(_Value: variant): pVariant;
 begin
 GetMem(Result, SizeOf(Variant));
 Result^ := _Value;
 end;


Seems pretty simple, doesnt it? Anybody who can spot the bug? I got spurious access violations in the line Result^ := _Value; Ok, the reason: Memory allocated with GetMem is not initialised, so the "Variant" pointed to by Result contains some random data, for example something that might represent a variant type which requires some finalisation when the variant is changed, lets say a variant array of some sort. But this finalisation wont work because the content is just some random garbage, and sometimes I was lucky (I mean that!) and got an access violation that allowed me to spot the error. The fix:


 function CreateVariantPtr(_Value: variant): pVariant;
 begin
 GetMem(Result, SizeOf(Variant));
 Initialize(Result^);
 Result^ := _Value;
 end;


Language: en
Source: Взято с сайта: http://www.swissdelphicenter.ch
ID: 00833