[fpc-devel] ref count issue with out param
    Martin Frb 
    lazarus at mfriebe.de
       
    Sat Jun 13 06:04:15 CEST 2015
    
    
  
Reading 
http://forum.lazarus.freepascal.org/index.php/topic,28740.msg180163.html#msg180163
and http://bugs.freepascal.org/view.php?id=28279
I did some tests and found something related, that I believe to be a 
bug. 2.6.4 and trunk (few weeks old)
Could someone please confirm?
The line
   s1 := copy(x,2,3)+'x';
creates a string with a refcount of 1 (for some reason if only using 
copy, but not +'x', then the ref count of S1 is 2)
The below outputs
0
0
0
-252645136
The 2nd call
   Foo2(s1,s1);
gets an invalid argument for "b"
The asm (trunk) is
.Ll26:
# [23] Foo2(s1,s1);
     movl    U_$P$PROJECT1_$$_S1,%ebx
     movl    $U_$P$PROJECT1_$$_S1,%eax
     call    fpc_ansistr_decr_ref
     movl    $U_$P$PROJECT1_$$_S1,%eax
     movl    %ebx,%edx
     call    P$PROJECT1_$$_FOO2$ANSISTRING$ANSISTRING
.Ll27:
ebx is a temp copy of s1, but then f1 becomes nil, and ebx points to 
freed memory.
program Project1;
procedure Foo1(a: AnsiString; out b: AnsiString);
begin
   WriteLn(length(a));  WriteLn(length(b));
   b := 'a';
end;
procedure Foo2(out a: AnsiString; b: AnsiString);
begin
   WriteLn(length(a));  WriteLn(length(b));
   b := 'a';
end;
const x: AnsiString = 'abcde';
var s1: AnsiString;
begin
   s1 := copy(x,2,3)+'x';
   Foo1(s1,s1);
   s1 := copy(x,2,3)+'x';
   Foo2(s1,s1);
   ReadLn;
end.
    
    
More information about the fpc-devel
mailing list