[fpc-pascal] Dynamic arrays, yet another pitfall

Sven Barth pascaldragon at googlemail.com
Sun Feb 9 17:46:03 CET 2014


On 09.02.2014 15:34, Jürgen Hestermann wrote:
> With the following declaration and code:
>
> -------------------
> var A,B: array of integer;
> ...
> SetLength(A,10);
> B := A;
> SetLength(B,20);
> -------------------
>
> both variables A and B point to the same array with 20 Elements.
> Changing A changes B and vice versa.

And again you did not provide a full compilable example. The following code

=== code begin ===

program tdynarrtest;

var
   a, b: array of LongInt;
begin
   SetLength(a, 10);
   b := a;
   SetLength(b, 20);
   Writeln(Length(a));
   Writeln(Length(b));
end.

=== code end ===

results in

=== output begin ===

10
20

=== output end ===

So exactly what I would expect from the COW mechanism.

Regards,
Sven



More information about the fpc-pascal mailing list