How to avoid memory leak if a fucntion returns TStringList and fails lazarus / 21-General ---------------------------------------------------------------------- BlueIcaro · 2022-11-04 11:50 Hello, I have a function which returns a TStringList. Every thing goes ok. But Imagine that the funcions raise a Error. I can't free the the StringList. This small code shows my problem Code: [Select]procedure TForm1.Button1Click(Sender: TObject); var   F: TStringList; begin   F := TestList;   try     try       ShowMessage(F.Text);     except       ShowMessage('Error');     end;   finally   FreeAndNil(F); //I got a exception here and TStringlist is not free   end; end; function TForm1.TestList: TStringList; begin   Result := TStringList.Create;   Result.Add('aaa');   //Some Error   raise Exception.Create('Fail'); end;     How can I make to free the TStringList Thanks /BlueIcaro ---------------------------------------------------------------------- itblumi · 2022-11-04 11:57 The point is you raise an error in your test method, so the Result will be free because of the Exception and your try except block can't catch this exception. ---------------------------------------------------------------------- itblumi · 2022-11-04 12:09 I would do something like this Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i procedure TForm1.Button1Click(Sender: TObject);var  F: TStringList;begin  try  try      F := TestList; // moved into the try except block to catch the exception, but the result of TestList could be nil      ShowMessage(F.Text);    except      on E: Exception do        ShowMessage(E.Message);    end;  finally    if (F <> nil) then // check if the StringList is created      FreeAndNil(F);  end; end; ---------------------------------------------------------------------- BlueIcaro · 2022-11-04 12:14 Hi, I don't know why, but the line always is true, and I got a exception: Code: [Select] if (F <> nil) then // check if the StringList is created       FreeAndNil(F); but this code works for me Code: [Select] procedure TForm1.Button1Click(Sender: TObject); var   F: TStringList; begin try     F := TestList;     ShowMessage(F.Text);     FreeAndNil(F);   except     ShowMessage('Error');   end; end; function TForm1.TestList: TStringList; begin   Result := TStringList.Create;   Result.Add('aaa');   //Some Error   FreeAndNil(Result);   raise Exception.Create('Fail'); end;     /[code] /BlueIcaro ---------------------------------------------------------------------- itblumi · 2022-11-04 12:17 It can be also that F is not initialized, so it points to a random point in the memory initialize it first with F := nil; ---------------------------------------------------------------------- itblumi · 2022-11-04 12:26 Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i procedure TForm1.Button1Click(Sender: TObject);var  F: TStringList;begin  try   F := nil;    try      F := TestList;      ShowMessage(F.Text);    except      ShowMessage('Error');    end;  finally    if (F <> nil) then      FreeAndNil(F);  end;end; function TForm1.TestList: TStringList;begin  Result := TStringList.Create;  Result.Add('aaa');  //Some Error  raise Exception.Create('Fail');end; ---------------------------------------------------------------------- itblumi · 2022-11-04 12:47 But it might be easier to catch the exception allready in your TestList function and return nil if an error occurs. Maybe something like this would be better: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i procedure Test1;var  F: TStringList;begin  try    F := nil;    F := TestList;  if (F <> nil) then      ShowMessage(F.Text);  finally    if (F <> nil) then      FreeAndNil(F);  end;end; function TestList: TStringList;begin  Result := TStringList.Create;  try    Result.Add('blabla');    raise Exception.Create('fail');  except    FreeAndNil(Result); // this is usally not need, because after the exception occurs all the vars will not exists anymore in the scope and should be free that's how it works in Delphi I'm not 100% sure in FPC  end;end;   Edit: FPC doesn't free the objects when an error occurs in the scope, so you have todo it by your self. ---------------------------------------------------------------------- piola · 2022-11-04 15:51 I might be wrong, but as far as I know, Code: [Select]if (x<>nil) then freeandnil(x) is redundant because Code: [Select]FreeAndNil should already perform this check. ---------------------------------------------------------------------- itblumi · 2022-11-04 16:02 Here is the code of FreeAndNil Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i      procedure FreeAndNil(var obj);      var        temp: tobject;      begin        temp:=tobject(obj);        pointer(obj):=nil;        temp.free;      end;   As you can see there is no check if it is nil or not ---------------------------------------------------------------------- BrunoK · 2022-11-04 16:08 Quote from: itblumi on November 04, 2022, 05:02:52 pmHere is the code of FreeAndNil Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i      procedure FreeAndNil(var obj);      var        temp: tobject;      begin        temp:=tobject(obj);        pointer(obj):=nil;        temp.free;      end;   As you can see there is no check if it is nil or not But : Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i       procedure TObject.Free;         begin           // the call via self avoids a warning           if self<>nil then             self.destroy;        end;So, yes it ends being checked against nil. ---------------------------------------------------------------------- itblumi · 2022-11-04 16:40 ok, I didn't look into this method. Then piola is right, but I will do it anywas because of compatibility with Delphi. But its actually crazy that you jump in a method of an none existing object ---------------------------------------------------------------------- Remy Lebeau · 2022-11-04 16:43 Quote from: BlueIcaro on November 04, 2022, 12:50:34 pmBut Imagine that the funcions raise a Error. I can't free the the StringList. Yes, you can, quite easily.  Simply catch the error, free the TStringList, and re-raise the error, eg: Code: [Select]procedure TForm1.Button1Click(Sender: TObject); var   F: TStringList; begin   F := TestList;   try     // use F as needed...   finally     F.Free;   end; end; function TForm1.TestList: TStringList; begin   Result := TStringList.Create;   try     Result.Add('aaa');     //Some Error     raise Exception.Create('Fail');   except     Result.Free;     raise;   end; end; ---------------------------------------------------------------------- alpine · 2022-11-04 17:18 Quote from: BlueIcaro on November 04, 2022, 01:14:02 pmHi, I don't know why, but the line always is true, and I got a exception: Code: [Select] if (F <> nil) then // check if the StringList is created       FreeAndNil(F); As itblumi noted, at the entry of Test1, space for variable F is allocated on stack but it is not initialized and holds some garbage (unlikely Nil). Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i if (F <> nil) thenCheck should be performed only with F explicitly initialized with Nil beforehand. Furthermore, when you allocate something into TestList you should take care to reclaim it also there in the case of exception. Returning Nil will signal the Test1 for the error or you can escalate with another raise as Remy Lebeau suggested. ---------------------------------------------------------------------- MarkMLl · 2022-11-04 21:11 Quote from: itblumi on November 04, 2022, 01:17:50 pmIt can be also that F is not initialized, so it points to a random point in the memory initialize it first with F := nil; That raises an interesting point: the failure mode might differ depending on whether the rubbish contained in the pointer satisfies the alignment criteria of the CPU architecture (in which case execution might continue until something /really/ goes wrong) or is immediately discerned to be a bad pointer. Quote from: itblumi on November 04, 2022, 05:40:28 pmBut its actually crazy that you jump in a method of an none existing object There's no easy way of determining that the memory location referred to by a pointer doesn't contain a valid object. The is operator can go some way towards it, but what's really needed is a checksum on each object (or, in general terms, memory block) that's invalidated when it's freed (or has never been assigned)... and I strongly suspect that that would be non-trivial to implement. MarkMLl ---------------------------------------------------------------------- itblumi · 2022-11-04 21:39 Quote from: MarkMLl on November 04, 2022, 10:11:24 pm Quote from: itblumi on November 04, 2022, 05:40:28 pmBut its actually crazy that you jump in a method of an none existing object There's no easy way of determining that the memory location referred to by a pointer doesn't contain a valid object. The is operator can go some way towards it, but what's really needed is a checksum on each object (or, in general terms, memory block) that's invalidated when it's freed (or has never been assigned)... and I strongly suspect that that would be non-trivial to implement. MarkMLl Maybe you understood me wrong. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i       procedure FreeAndNil(var obj);      var        temp: tobject;      begin        temp:=tobject(obj);        pointer(obj):=nil;        temp.free;       end;   FreeAndNil(nil); // I find it crazy that this is working, that's kinda magic XD  I was actually expecting that temp.Free; will crash there because its like nil.Free; or call a method of not existing object even when its nil . I totally understand that its really hard to check if a pointer points to the wrong memory address. ---------------------------------------------------------------------- jamie · 2022-11-05 14:40 Catching traps like that is hard at times. Normally I preset the results to NIL. This way if an unexpected crash happens you can at least know that its NIL on return.  There is always that chance or a case where the return externally may not be reached property due to how the compiler maintains the return values for those that can set in a register and thus does this local until the end and if the end never comes? A Reference return would most likely be more reliable, but we can't have everything can we? ---------------------------------------------------------------------- PascalDragon · 2022-11-05 20:48 Quote from: itblumi on November 04, 2022, 05:40:28 pmok, I didn't look into this method. Then piola is right, but I will do it anywas because of compatibility with Delphi. Delphi's TObject.Free is implemented the same way as FPC's. Quote from: itblumi on November 04, 2022, 10:39:43 pmQuote from: MarkMLl on November 04, 2022, 10:11:24 pm Quote from: itblumi on November 04, 2022, 05:40:28 pmBut its actually crazy that you jump in a method of an none existing object There's no easy way of determining that the memory location referred to by a pointer doesn't contain a valid object. The is operator can go some way towards it, but what's really needed is a checksum on each object (or, in general terms, memory block) that's invalidated when it's freed (or has never been assigned)... and I strongly suspect that that would be non-trivial to implement. MarkMLl Maybe you understood me wrong. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i       procedure FreeAndNil(var obj);      var        temp: tobject;      begin        temp:=tobject(obj);        pointer(obj):=nil;        temp.free;       end;   FreeAndNil(nil); // I find it crazy that this is working, that's kinda magic XD  I was actually expecting that temp.Free; will crash there because its like nil.Free; or call a method of not existing object even when its nil . You can call any non-virtual method with an invalid Self and it will go well as long as you don't access any field or property or call a virtual method as there is no check for the Self itself. This is why TObject.Free can do what it does. Quote from: BlueIcaro on November 04, 2022, 12:50:34 pmHello, I have a function which returns a TStringList. Every thing goes ok. But Imagine that the funcions raise a Error. I can't free the the StringList. This small code shows my problem Code: [Select]procedure TForm1.Button1Click(Sender: TObject); var   F: TStringList; begin   F := TestList;   try     try       ShowMessage(F.Text);     except       ShowMessage('Error');     end;   finally   FreeAndNil(F); //I got a exception here and TStringlist is not free   end; end; function TForm1.TestList: TStringList; begin   Result := TStringList.Create;   Result.Add('aaa');   //Some Error   raise Exception.Create('Fail'); end;     How can I make to free the TStringList When an exception occurs inside a function and assignment of the function result doesn't take place as execution will immediately move to the next suitable exception handler (be it finally or except). Thus to correctly handle a possible memory leak you need to follow Remy Lebeau's suggestion to free the stringlist inside your TestList function upon an exception and reraising the exception. ---------------------------------------------------------------------- Чебурашка · 2022-11-07 15:21 Quote from: BlueIcaro on November 04, 2022, 12:50:34 pmHello, I have a function which returns a TStringList. Every thing goes ok. But Imagine that the funcions raise a Error. I can't free the the StringList. This small code shows my problem Code: [Select]procedure TForm1.Button1Click(Sender: TObject); var   F: TStringList; begin   F := TestList;   try     try       ShowMessage(F.Text);     except       ShowMessage('Error');     end;   finally   FreeAndNil(F); //I got a exception here and TStringlist is not free   end; end; function TForm1.TestList: TStringList; begin   Result := TStringList.Create;   Result.Add('aaa');   //Some Error   raise Exception.Create('Fail'); end;     How can I make to free the TStringList Thanks /BlueIcaro It seems that the problem is that the function TestList returns in two alternative modes, one without error, and in this case the Result variable is set and passed back to the caller (if the caller takes it and uses it - and frees it), the other with error, and in that case the Result vairable in still set, but caller wont receive it. Simply trap inside the function when a exception is generated, and cleanup the Result before re-raising the exception because you know that caller won't ever receive that value at all. Code: [Select]function TForm1.TestList: TStringList; begin   Result := TStringList.Create;   try      Result.Add('aaa');      //Some Error      raise Exception.Create('Fail');   except     Result.Destroy();     raise;  // re-raise   end; end; Later fix the calling function because for how is written now, it doesn't trap anything. Code: [Select]procedure TForm1.Button1Click(Sender: TObject); var   F: TStringList; begin   try     F := TestList; // if does not return is because of an exception, and in such case F does not matter because is not set at all.     try       // If code here might raise then enclose it in a try ... except, in this moment it doesn't       ShowMessage(F.Text);     finally       F.Destroy();     end;   except     ShowMessage('Error');   end; end; ---------------------------------------------------------------------- itblumi · 2022-11-07 18:03 I checked it and you are right, but FreeAndNil fails when you try to Free a reference in an object which doesnt exist anymore. That's properly why I did it everytime, but you can't check it then anyways. ---------------------------------------------------------------------- Warfley · 2022-11-07 20:39 Quote from: itblumi on November 04, 2022, 10:39:43 pmI was actually expecting that temp.Free; will crash there because its like nil.Free; or call a method of not existing object even when its nil . I totally understand that its really hard to check if a pointer points to the wrong memory address. This is the whole point of Free, the actual destructor is Destroy, the only point of calling Free instead of Destroy is because Free does the extra nil check to bring a little bit of robustness with it. To get to the topic, the best solution is to not return newly created objects from functions that can raise exceptions. While Remys suggestion works, it is actually not that nice because a. it requires additonal boilerplate code, but also because lazarus will report the exception when re-raising at each instance it is cought, so it will halt the debugger effectively twice, which can be annoying. The much simpler solution here is to just avoid this. This can either be done by using var paramters: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i procedure CreateList(var Result: TStringList);begin// Fill Resultend; // useMyList := TStringList.Create;try  CreateList(MyList);finally  MyList.Free;end;or, use constructors, because here the fpc automatically generates code for cleaning it up: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i type  TMyList = class(TStringList)  public constructor CreateList;  end; constructor TMyList.CreateList;begin  inherited Create;  // Fill Listend; var  MyList: TStringList;begin  MyList := TMyList.CreateList;  try    // Do something with the list  finally    MyList.Free;  end;end; So you have the choice which hacky solution you want to have, either the one where you have to catch, free and re-raise the exception in the function, or where you just don't use a function but rather a var parameter, or create a constructor. None of them is very pretty, but thats just the problems with manual memory management, it sucks. ---------------------------------------------------------------------- PascalDragon · 2022-11-08 06:32 Quote from: itblumi on November 07, 2022, 07:03:47 pmI checked it and you are right, but FreeAndNil fails when you try to Free a reference in an object which doesnt exist anymore. That's properly why I did it everytime, but you can't check it then anyways. If FreeAndNil fails that means that the value passed in is not Nil (or the destructor raises an exception, but as you said, the instance doesn't exist anymore, so that won't be the problem ). FreeAndNil will only set the instance variable to Nil that you pass in, but not any other that might point to the same class: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i {$mode objfpc} uses  SysUtils; var  o1, o2: TObject;begin  o1 := TObject.Create;  o2 := o1;   Writeln('o1: ', HexStr(Pointer(o1)), ', o2: ', HexStr(Pointer(o2)));   // this will leave o2 as is  FreeAndNil(o1);   Writeln('o1: ', HexStr(Pointer(o1)), ', o2: ', HexStr(Pointer(o2)));   // o2 is not Nil, so destructor will be called again -> boom  FreeAndNil(o2);   Writeln('o1: ', HexStr(Pointer(o1)), ', o2: ', HexStr(Pointer(o2)));end. ---------------------------------------------------------------------- SymbolicFrank · 2022-11-08 09:12 It might be an open door, but did anyone suggest not to raise exceptions in functions that return unmanaged function results? As Warfley said, use var parameters, if you really want to raise that exception. Also, what makes FreeAndNill better in this case? It's not a solution to the underlying problem. And last, you don't need to use manual memory management. You can make a class that inherits from TInterfacedObject, add and implement the IUnknown interface, or use a smart pointer. ---------------------------------------------------------------------- MarkMLl · 2022-11-08 09:25 Quote from: SymbolicFrank on November 08, 2022, 10:12:30 amuse var parameters, if you really want to raise that exception. var parameter, or out parameter? ISTM that it would be rare for the programmer to want to pass something in (unless the intention was "create a stringlist if none exists") so the compiler should be given the maximum number of hints for pre/postcondition checking. MarkMLl ---------------------------------------------------------------------- alpine · 2022-11-08 10:13 Quote from: Warfley on November 07, 2022, 09:39:30 pm*snip* The much simpler solution here is to just avoid this. This can either be done by using var paramters: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i procedure CreateList(var Result: TStringList);begin// Fill Resultend; // useMyList := TStringList.Create;try  CreateList(MyList);finally  MyList.Free;end;How the var parameter makes any difference? It just adds another reference. I don't get it. Quote from: Warfley on November 07, 2022, 09:39:30 pmor, use constructors, because here the fpc automatically generates code for cleaning it up: *snip* IMO it doesn't. The following program: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i program Project1; uses  Classes; type  TMyList = class(TStringList)  public  constructor CreateList;  end; constructor TMyList.CreateList;var  I, J: Integer;begin  inherited Create;  Add('ABC');  Add('DEF');  J := 0;  I := 14 div J;  // Fill Listend; var  MyList: TStringList;begin  MyList := TMyList.CreateList;  try    try      // Do something with the list    finally      MyList.Free;    end;  except  end;end. Gives the following with heaptrc enabled: Code: Text  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i An unhandled exception occurred at $00401787:EDivByZero: Division by zero  $00401787  CREATELIST,  line 20 of Project1.pas  $004017FA  main,  line 27 of Project1.pas Heap dump by heaptrc unit of C:\AI\_\test_ctrcleanup\project1.exe463 memory blocks allocated : 42817/43160461 memory blocks freed     : 42661/430002 unfreed memory blocks : 156True heap size : 327680 (96 used in System startup)True free heap : 327200Should be : 327232Call trace for block $000AB8D8 size 64  $775B6C99  $775B6C6B  $775B6AF7  $004017FA  main,  line 27 of Project1.pas  $004017FA  main,  line 27 of Project1.pasCall trace for block $000A39A0 size 92  $00428CB5  $0040FBA0  $775B6C99  $775B6C6B  $775B6AF7  $004017FA  main,  line 27 of Project1.pas  $004017FA  main,  line 27 of Project1.pas And the following with 20-th line commented (no zerodiv): Code: Text  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i Heap dump by heaptrc unit of C:\AI\_\test_ctrcleanup\project1.exe115 memory blocks allocated : 2798/3104115 memory blocks freed     : 2798/31040 unfreed memory blocks : 0True heap size : 163840 (96 used in System startup)True free heap : 163744 I don't think the advise is relevant. Or maybe I'm missing something? ---------------------------------------------------------------------- Warfley · 2022-11-08 10:31 Quote from: y.ivanov on November 08, 2022, 11:13:24 amHow the var parameter makes any difference? It just adds another reference. I don't get it. Simple, with the var the object is created in the calling function not in the function that is called. Therfore if an exception is raised within the function that is called, the object is surely already created (because creation is under control of the calling function) and as the exception raising function is in the try finally block it will be freed without having to rely on a potentially undefined function result. The main problem is that if a function raises an exception, the result is undefined, so you can't know if it was now created and needs to be freed, or not. So by moving the creation out of the function, if that function raises an exception you already know that the object is created and therefore avoid the undefined state QuoteQuote from: Warfley on November 07, 2022, 09:39:30 pmor, use constructors, because here the fpc automatically generates code for cleaning it up: *snip* IMO it doesn't. The following program: [...] I don't think the advise is relevant. Or maybe I'm missing something? You are not Using sysutils, I think that is required for exceptions to work properly. My example: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i program Test; {$mode objfpc}{$H+} uses  Heaptrc, SysUtils, Classes; type  TTestList = class(TStringList)    constructor Create;  end; constructor TTestList.Create;begin  raise Exception.Create('Test');end; var  lst: TTestList;begin  try    lst := TTestList.Create;    WriteLn(lst.Text);  except on E: Exception do    WriteLn('Exception: ', E.Message);  end;end. Output: Code: Text  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i $> fpc .\test.pasFree Pascal Compiler version 3.2.2 [2022/05/15] for x86_64Copyright (c) 1993-2021 by Florian Klaempfl and othersTarget OS: Win64 for x64Compiling .\test.pasLinking test.exe27 lines compiled, 0.2 sec, 178720 bytes code, 10180 bytes data$> .\test.exeException: TestHeap dump by heaptrc unit of test.exe118 memory blocks allocated : 4573/4880118 memory blocks freed     : 4573/48800 unfreed memory blocks : 0True heap size : 196608 (160 used in System startup)True free heap : 196448As you can see, no memory leak EDIT: Also in your example you are not catching the exception raised by the constructor, which means that the internal fpc raise function will detect no exception handler (or finally block), and therefore stop the execution immediately, before the memory of the constructor can be freed. If I change your code to be: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i   try // Put try except around the creation    MyList := TMyList.CreateList;  try      // Do something with the list    finally      MyList.Free;  end;  except  end;No memory leak ---------------------------------------------------------------------- alpine · 2022-11-08 11:06 Quote from: Warfley on November 08, 2022, 11:31:07 amQuote from: y.ivanov on November 08, 2022, 11:13:24 amHow the var parameter makes any difference? It just adds another reference. I don't get it. Simple, with the var the object is created in the calling function not in the function that is called. Therfore if an exception is raised within the function that is called, the object is surely already created (because creation is under control of the calling function) and as the exception raising function is in the try finally block it will be freed without having to rely on a potentially undefined function result. Sure, but the var isn't making any difference. You're just passing a reference to another reference. Quote from: Warfley on November 08, 2022, 11:31:07 amThe main problem is that if a function raises an exception, the result is undefined, so you can't know if it was now created and needs to be freed, or not. So by moving the creation out of the function, if that function raises an exception you already know that the object is created and therefore avoid the undefined state QuoteQuote from: Warfley on November 07, 2022, 09:39:30 pmor, use constructors, because here the fpc automatically generates code for cleaning it up: *snip* IMO it doesn't. The following program: [...] I don't think the advise is relevant. Or maybe I'm missing something? You are not Using sysutils, I think that is required for exceptions to work properly. My example: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i program Test; {$mode objfpc}{$H+} uses  Heaptrc, SysUtils, Classes; type  TTestList = class(TStringList)    constructor Create;  end; constructor TTestList.Create;begin  raise Exception.Create('Test');end; var  lst: TTestList;begin  try    lst := TTestList.Create;    WriteLn(lst.Text);  except on E: Exception do    WriteLn('Exception: ', E.Message);  end;end. Output: Code: Text  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i $> fpc .\test.pasFree Pascal Compiler version 3.2.2 [2022/05/15] for x86_64Copyright (c) 1993-2021 by Florian Klaempfl and othersTarget OS: Win64 for x64Compiling .\test.pasLinking test.exe27 lines compiled, 0.2 sec, 178720 bytes code, 10180 bytes data$> .\test.exeException: TestHeap dump by heaptrc unit of test.exe118 memory blocks allocated : 4573/4880118 memory blocks freed     : 4573/48800 unfreed memory blocks : 0True heap size : 196608 (160 used in System startup)True free heap : 196448As you can see, no memory leak EDIT: Also in your example you are not catching the exception raised by the constructor, which means that the internal fpc raise function will detect no exception handler (or finally block), and therefore stop the execution immediately, before the memory of the constructor can be freed. It is same as original yours - just copied it and added 2x Add() and zero division to generate an exception. You have modified your example in here-quoted post ( lst := TTestList.Create; now is in the try block) Please, correct your posts in the way you intended them to be. Now they are misleading. Regards, ---------------------------------------------------------------------- Warfley · 2022-11-08 13:13 Quote from: y.ivanov on November 08, 2022, 12:06:36 pmSure, but the var isn't making any difference. You're just passing a reference to another reference.Ah now I understand what you mean, you are right, this is not necessary here, unless you might want to change the value (e.g. by nilling it). QuoteIt is same as original yours - just copied it and added 2x Add() and zero division to generate an exception. You have modified your example in here-quoted post ( lst := TTestList.Create; now is in the try block) Please, correct your posts in the way you intended them to be. Now they are misleading. Regards, See my last edit, there must be at least one try block for this to work. Otherwise the memory won't be freed. I don't know if this is a bug or intendet, but if we look at the internal fpc_RaiseException function called when an exception is raised: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i procedure fpc_RaiseException (Obj : TObject; AnAddr : CodePointer; AFrame : Pointer);[Public, Alias : 'FPC_RAISEEXCEPTION']; compilerproc;var  _ExceptObjectStack : PExceptObject;  _ExceptAddrstack : PExceptAddr;begin{$ifdef excdebug}  writeln ('In RaiseException');{$endif}  if ExceptTryLevel<>0 then    Halt(217); We see that the very first thing that happens is, if it's not in a try block, it will immediately shutdown the application, not executing the cleanup code that is automatically registered by the constructor on the exception stack, as part of the usuall exception raising mechanism later in that function. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i   if (RaiseProc <> nil) and (_ExceptObjectStack <> nil) then    with _ExceptObjectStack^ do      RaiseProc(FObject,Addr,FrameCount,Frames); Therefore the memory does not get freed. But this isn't a problem in reality, because when the application is forcefully closed (what the halt does in this context) the OS will cleanup all the memory anyway, so there isn't really a memory leak, because it is created by closing the application, which will dispose all of the memory anyway. It just doesn't look nice in the heaptrc. This kinda feels like a bug (as the constructor basically registers a hidden except but the ExceptTryLevel does not seem to be incremented), but maybe that has a reason ---------------------------------------------------------------------- alpine · 2022-11-08 15:40 Quote from: Warfley on November 08, 2022, 02:13:42 pm*snip* See my last edit, there must be at least one try block for this to work. Otherwise the memory won't be freed. Perhaps you're talking about the automatic cleanup performed by the compiler on the managed variables and also in the specific case when an exception is raised into the constructor (destructor called automatically, memory for *that* object reclaimed, etc.). But note that the OP question was different and it was your advice to fill the TStringList into a constructor. Note also that in the original OP post, there is an Add() to the list, something that cannot be automatically reverted by the compiler, but only with a dedicated destructor which must be aware that the object is only partially constructed ... the problem just shifted from the function to the constructor/destructor pair ... anyway, I find Remy answer to be relevant - no need to over-complicate things. Regards, ---------------------------------------------------------------------- SymbolicFrank · 2022-11-08 15:47 If something happens in the constructor and you cannot return an instance, use 'Fail'. The thing with the 'var' parameter is, that you don't create the object in the function that can raise the exception, you pass that object as a parameter. A collection of three examples: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i type  TTestList = class(TStringList)    constructor Create;  end; constructor TTestList.Create;begin  Fail;end; //.. function ReturnObject: TStringList;begin  Result := nil;   try    Result := TStringList.Create;  except    // Whatever  end;   // Fill it with stuff end; //.. procedure BeSafe(var sl: TSTringList): Boolean;begin  Result := True;   try    // Do stuff with sl  except    Result := False;  end; end; ---------------------------------------------------------------------- Warfley · 2022-11-08 16:38 Quote from: y.ivanov on November 08, 2022, 04:40:43 pmthe problem just shifted from the function to the constructor/destructor pair ... anyway, I find Remy answer to be relevant - no need to over-complicate things. Yes it is still the same problem as with a try-except re-raise, but it has one significant advantage, when debugging, the debugger doesn't stop twice for the same exception. If you are dealing with a lot of exceptions, this is really anoying. It is an ugly hacky solution, but so is the try-catch-reraise approach, it's just a bit more comfortable when debugging. Also it is conceptually often advantagious for the structuring of your project if you make sure that only constructors create instances of a certain class. For example, instead of reading a key value store into a stringlist, you can have a key value store class which has a loading constructor. This way you have all the functionality that belongs to the key value store in one place and know exactly that all the ways to create it are constructors. So it can be a way of cleaning up your code ---------------------------------------------------------------------- ASerge · 2022-11-08 23:01 Quote from: SymbolicFrank on November 08, 2022, 04:47:58 pmIf something happens in the constructor and you cannot return an instance, use 'Fail'. I would not recommend using Fail. Firstly, most often no one checks that the result of calling the constructor is equal to nil. Secondly, the destructor is not called, which means that resources that could have been allocated in the constructor earlier or in the base constructor are not cleaned up. It is better to raise an exception for errors in the constructor. ---------------------------------------------------------------------- PascalDragon · 2022-11-09 06:36 Quote from: SymbolicFrank on November 08, 2022, 04:47:58 pmIf something happens in the constructor and you cannot return an instance, use 'Fail'. Fail is a remnant of the TP style object type and should have never been allowed for classes, because it doesn't work correctly there in all cases. Don't use.