Assigning open array

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Assigning open array

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.

_______________________________________________
fpc-pascal maillist  -  [hidden email]
http://lists.freepascal.org/cgi-bin/mailman/listinfo/fpc-pascal
Reply | Threaded
Open this post in threaded view
|

Re: Assigning open array

dmitry boyarintsev
On Tue, Jul 31, 2018 at 11:39 AM Santiago A. <[hidden email]> 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

_______________________________________________
fpc-pascal maillist  -  [hidden email]
http://lists.freepascal.org/cgi-bin/mailman/listinfo/fpc-pascal