[fpc-devel] Const optimization is a serious bug

Mattias Gaertner nc-gaertnma at netcologne.de
Thu Jul 7 12:43:10 CEST 2011


 
 

 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.
 
 

 >[...]

 Mattias
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-devel/attachments/20110707/24cde9b2/attachment.html>


More information about the fpc-devel mailing list