Recent

Author Topic: FormatFloat possible improvement  (Read 333 times)

bytebites

  • Hero Member
  • *****
  • Posts: 707
FormatFloat possible improvement
« on: March 08, 2025, 10:20:12 pm »

Code: Pascal  [Select][+][-]
  1. Function FormatFloat(Const Format : String; Value : Extended; Const FormatSettings: TFormatSettings) : String;
  2.  
  3. Var
  4.   buf : Array[0..1024] of Char;
  5.   Len: Integer;
  6.  
  7. Begin
  8.   Len:=FloatToTextFmt(PChar(@Buf[0]),Value,PChar(Format),FormatSettings);
  9.   Buf[Len]:=#0;
  10.   Result:=StrPas(Pchar(@Buf[0]));
  11. End;
  12.  

Currently FormatFloat function uses StrPas to create result, is it possible to use SetString instead since the length is known?

ASerge

  • Hero Member
  • *****
  • Posts: 2389
Re: FormatFloat possible improvement
« Reply #1 on: March 09, 2025, 02:09:58 pm »
I suggest making it more safe:
Code: Pascal  [Select][+][-]
  1. function FormatFloat(const Format: string; Value: Extended; const FormatSettings: TFormatSettings): string;
  2.  
  3.   procedure FormatCommon(Buf: PChar);
  4.   var
  5.     Len: SizeInt;
  6.   begin
  7.     Len := FloatToTextFmt(@Buf[0], Value, PChar(Format), FormatSettings);
  8.     SetString(Result, Buf, Len);
  9.   end;
  10.  
  11.   procedure FormatDynamicBuf;
  12.   var
  13.     Buf: PChar;
  14.   begin
  15.     Buf := GetMem(Length(Format) + 100);
  16.     try
  17.       FormatCommon(Buf);
  18.     finally
  19.       FreeMem(Buf);
  20.     end;
  21.   end;
  22.  
  23. var
  24.   Buf: array[Byte] of Char;
  25. begin
  26.   if Length(Format) < 100 then
  27.     FormatCommon(Buf)
  28.   else
  29.     FormatDynamicBuf;
  30. end;

A simple test where the original gives an AV:
Code: Pascal  [Select][+][-]
  1. procedure TForm1.Button1Click(Sender: TObject);
  2. var
  3.   LongFormat: string;
  4. begin
  5.   Memo1.Text := FormatFloat('0000', 0.0, DefaultFormatSettings);
  6.   LongFormat := StringOfChar('0', 2000);
  7.   Memo1.Append(FormatFloat(LongFormat, 0.0, DefaultFormatSettings));
  8. end;

AlexTP

  • Hero Member
  • *****
  • Posts: 2544
    • UVviewsoft
Re: FormatFloat possible improvement
« Reply #2 on: March 09, 2025, 03:38:39 pm »
@bytebites
I suggested the same in GitLab issue, without reading this topic.
https://gitlab.com/freepascal.org/fpc/source/-/issues/41181

 

TinyPortal © 2005-2018