Sign in Join

Live chat for Free Pascal, Lazarus, Delphi and every Pascal programmer.

Mailing lists / fpc-pascal / 2018-07

Assigning open array

2 messages · 2 people ·

Reply by email Subscribe to this list Your subscription

Read-only archive. Use j and k to move between messages.

Santiago A.

Hello:
I'm not very sure how open arrays are copied

program Project1;
Type
  TMyRecord=record
             somedata:string;
             ArrayInt:array of integer;
            end;
  TRecordList=array of TMyRecord;
procedure foo(out aList:TRecordList);
var
  TmpList:TRecordList;
begin
   SetLength(TmpList,1);
   tmpList[0].somedata:='sssss';
   SetLength(tmpList[0].ArrayInt,1);
   tmpList[0].ArrayInt[0]:=5;
   SetLength(aList,0);
   aList:=copy(TmpList,0,1);
end;
var
  MyList:TRecordList;
begin
   foo(MyArray);
   writeln(MyList[0].somedata); // prints sssss
   writeln(MyList[0].ArrayInt[0]); // prints 5
   readln;
end.

I looks like working fine.  MyArray.ArrayInt[0] is still 5. But I wonder whether it is really right or just luck. Open arrays are pointers, so, when tmpList gets out of scope then tmpList.arrayInt is freed. I want to be sure that that my example is not working just because it happens that the memory that used TmpList[0].arrayInt[0] hasn't been overwritten. Does the copy function at the end of  foo just copies the reference and, after tmpList gets out scope, it points nowhere? or does it clone arrayInt? or does it have some kind of reference counter like with strings?

Saludos Santiago A.

Reply by email

Dmitry Boyarintsev
to Santiago A.
AM Santiago A. wrote
I'm not very sure how open arrays are copied

In your example you don't have open arrays used - you have dynamic arrays.

I looks like working fine. MyArray.ArrayInt[0] is still 5. But I wonder whether it is really right or just luck. Open arrays are pointers, so, when tmpList gets out of scope then tmpList.arrayInt is freed.

The compiler is aware of managed (reference counted) type fields within a dynamic array body.
Thus each ArrayInt in "aList" would have reference count increased. Thus when tmpList is released ArrayInt stays, as its reference count doesn't reach zero.

thanks,
Dmitry

Reply by email