[fpc-devel] Const optimization is a serious bug

michael.vancanneyt at wisa.be michael.vancanneyt at wisa.be
Thu Jul 7 13:10:52 CEST 2011



On Thu, 7 Jul 2011, Mattias Gaertner wrote:

>  
>  
>
> Martin <fpc at mfriebe.de> hat am 7. Juli 2011 um 12:20 geschrieben:
>
> > On 07/07/2011 07:51, Alexander Klenin wrote:
> >[...]
> > >> 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. 
> You don't need the future. You can already create a crash using const
> shortstring:
>  
>  
> {$mode objfpc}{$H+}
> uses Classes;
> var
>   s: shortstring = '';
>   o: TStringList = nil;
>
> procedure DoSomething(const h: shortstring);
> begin
>   if h<>'' then
>     o:=TStringList.Create; // not called, because s=h=''
>   s:='A';
>   if h<>'' then
>     writeln(o.Count); // called, because now s=h='A' => crash
> end;
>
> begin
>   DoSomething(s);
> end.

Sigh....

That's what I've been saying all along. You don't even need strings for it.
Plain records and integers will do it just as well.

Michael.


More information about the fpc-devel mailing list