On 23/02/2025 20:42, Martin Frb wrote:
function Foo: ansistring;
var s: ansistring;
begin
  SetLenght(s, 10000); fillchar(@s[1], 10000, ' ');
  SetLenght(Result, 10000); fillchar(@Result[1], 10000, ' ');
end;

...
So in the original example above, if either string is having a large content (pointing to a length = 1MB chars area), then SetLengh would copy "10000" chars of that into the new unique string.
Such a copy would be an unnecessary cost.

I know this will happen (with smaller length) when using -gt.
But will it ever happen in any other case?


So yes I found an example for result. The length of result will have the previous value.

program Project1; {$Mode objfpc}

function bar: AnsiString;
begin
  writeln(Length(Result));
  SetLength(Result, random(20));
end;

procedure foo;
var   a: String;
begin
  repeat     a := bar;   until a = '';
end;

begin
  foo;  readln;
end.


Leaves the question: What about local vars?





-------------------
As a side note

program Project1;
procedure foo;
var
  s: ansistring;
begin
  SetLength(s, 100);
end;

begin
  foo;
end.

Compile with -O3 and somehow the compiler realizes that s is initialized. The warning is gone.

Interestingly -O3 will also do that for "result" in "function foo: ansistring;" => Doesn't that depend on the caller, or is there some magic?

Any idea why -O3 does not print the warning?

In my new example "result" will be having the previous value, even with O3. So it should be giving that warning?

_______________________________________________
fpc-devel maillist  -  fpc-devel@lists.freepascal.org
https://lists.freepascal.org/cgi-bin/mailman/listinfo/fpc-devel

Reply via email to