Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the program crash when using const string arguments?

My program has following code:

function FooBar(const s: string): string;
var
  sa: AnsiString;
begin

  // ..........................

  sa := AnsiString(s);
  sa := AnsiString(StringReplace(string(sa), '*', '=', [rfReplaceAll]));
  sa := AnsiString(StringReplace(string(sa), ' ', '+', [rfReplaceAll]));
  result := string(sa);

  // ..........................

end;

I noticed that the program did crash "somewhere" and FastMM4 said that I had written to a freed object. As soon as I have commented out "const", the program did work.

I have read the Delphi documentation about const arguments, but I can't figure out why the const argument crashes the program. I would love to understand it.

UPDATE: The program does only crash in Delphi 6 and only if optimization is ON. If the optimization is OFF, the program will work normally. Might it be a Delphi bug?

like image 768
Daniel Marschall Avatar asked Apr 29 '14 10:04

Daniel Marschall


1 Answers

There are a few peculiar gotchas when it comes to const string parameters.
Many years ago I helped a colleague resolve a similar peculiar problem (D3 iirc). The following simplified example doesn't look like your specific issue, but it may give you some ideas:

type
  TMyClass
    FString: string;
    procedure AppendString(const S: string);
  end;

procedure TMyClass.AppendString;
begin
  FString := FString + S;
end;

Now if you have an instance of TMyClass and try to call AppendString(FString); to double up the string, you may get an access violation. (There are a few other factors that can affect if you do.) The reason is as follows:

  • The const prevents refcounting the string on the method call.
  • So FString may have refCount = 1 when its value is changed.
  • In which case Copy-on-Write doesn't apply and the string is reallocated. (Most likely at a different address.)
  • So when the method returns, S is referring to an invalid address, and triggers an AV.
like image 152
Disillusioned Avatar answered Oct 21 '22 13:10

Disillusioned