[fpc-devel] Const optimization is a serious bug

Martin fpc at mfriebe.de
Thu Jul 7 12:20:50 CEST 2011


On 07/07/2011 07:51, Alexander Klenin wrote:
> On Thu, Jul 7, 2011 at 17:45, Florian Klaempfl<florian at freepascal.org>  wrote:
>>> Put in another words, current "const string" implementation honors the
>>> implicit contract of
>>> "adding const in front of the string parameter cancels refcounting",
>>> at the cost of breaking the implicit contract of "refcounted values
>>> are indistinguishable
>>> from simple values (except maybe in performance)".
>> As I have shown before in this thread, non ref. counted values e.g.
>> shortstrings are affected by the same problem.
> And as per Chad's reply (and agree with his logic), this is not so.


Well  it's not as obvious)

In Florian's  example the "const" param follows the value of the 
original variable (so yes it does something that is unexpected)
But with short string it does not crash. there is no ref count going 
wrong, there is no memory being freed while still in use.

Yet he is 100% right it's the same problem, the same error, and as severe.

Because the behaviour is not guaranteed.
The compiler (in future versions) could make optimizations knowing that 
the "const s: shortstring" (or "const x: sometype") doesn't change.

And that means, in future such code could behave different or even 
crash, only by change of content (even if memory is not freed).
Hence yes, it is as severe as with ansistrings. It only is not yet as 
visible.


Here is the example as provided by Florian:

var
   s : shortstring;

procedure p(const s1 : shortstring);
   begin
     s:='Ops';
     writeln(s1);
   end;

begin
   s:='Hello world';
   p(s);
end.






More information about the fpc-devel mailing list