TBufferedFileStream crashes in SetSize()
Free Pascal Compiler version 3.2.3-772-gd520814a [2023/09/05] for x86_64 (Linux).
I use this code to save some lines to file.
{$mode objfpc}
{$h+}
uses sysutils, classes, bufstream;
procedure Save(const filename: string; L: TStringList);
var
fs: TBufferedFileStream; //improves saving speed a lot
NMode: word;
buf: string;
i: integer;
begin
NMode:= fmOpenReadWrite or fmShareDenyWrite;
//don't set fmCreate for existing file, to keep NTFS file streams
if not FileExists(filename) then
NMode:= NMode or fmCreate;
fs:= TBufferedFileStream.Create(filename, NMode);
try
fs.Size:= 0; // <------- crash
for i:= 0 to L.Count-1 do
begin
buf:= L[i]+#10;
fs.WriteBuffer(buf[1], length(buf));
end;
finally
FreeAndNil(fs);
end;
end;
var
L: TStringList;
begin
L:= TStringList.Create;
L.Add('line one;');
L.Add('line two;');
L.Add('line end;');
Save('test.log', L);
L.Clear;
L.Add('line one;');
Save('test.log', L);
L.Free;
end.
fs.Size:=0
is nessesary - without it, old contents of the file will be kept and smaller file (created with the 2nd call of Save) will be having tail from old content (from the 1st call of Save).
But, app now crashes on fs.Size:=0
. SIGSEGV.
Asm window:
BUFSTREAM$_$TBUFFEREDFILESTREAM_$__$$_SETSIZE64$INT64
000000000047EDD0 53 push rbx
000000000047EDD1 4154 push r12