try-finally - resource release (fpc/lazarus) lazarus / 21-General ---------------------------------------------------------------------- sunjob · 2022-04-19 15:23 try-finally - resource release (fpc/lazarus) good day/night! I read someone else's code, "there is a misunderstanding" 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 beginvar ResponceStream := PostRequest(UrlCtrl + '/api/hello', PostSource);try// here voidfinally  ResponceStream.Free;  end;end;  asked the author: Quoteis it pointless to use the try-finally construct in this way? if something happens in the process of sending a request, then the resource will not be released got the answer: Quoteon the contrary, there will certainly be a liberation explain why? :о) Thank YOU p.s. this code from Delphi, i'm translate to Lazarus ---------------------------------------------------------------------- marcov · 2022-04-19 15:33 That 's not valid FPC/Lazarus code. ---------------------------------------------------------------------- sunjob · 2022-04-19 15:37 this code from Delphi, i'm translate to Lazarus ---------------------------------------------------------------------- marcov · 2022-04-19 15:41 It will be freed (finally executes always), but the try finally is essentially useless, as it doesn't protect against exceptions anywhere (most  notably postrequest). ---------------------------------------------------------------------- Warfley · 2022-04-19 15:47 The try-except block should always be after the assignment, because the value of the variable is undefined if the assignment itself threw the exception. For 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 function ExceptionTest: TStringList;begin  Raise Exception.Create('Test');  Result := TStringList.Create;end; procedure Test;var sl: TStringList;begin  try    sl := ExceptionTest;  finally    sl.Free;  end;end; This gives a segfault on the sl.Free, because the assignment never got through. Also note that this does not produce a memory leak, because the "TStringList.Create" is called after the exception, so when the exception is raised, the result has not been created and therefore does not need freeing. So when compiling this with heraptrc: 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 function ExceptionTest: TStringList;begin                   Raise Exception.Create('Test');         Result := TStringList.Create;end; procedure Test;var sl: TStringList;begin  sl := ExceptionTest;  try  finally    sl.Free;  end;end;We see no memory leak 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 2 memory blocks allocated : 76/802 memory blocks freed     : 76/800 unfreed memory blocks : 0True heap size : 262144 (2464 used in System startup)True free heap : 259680 If you turn it the other way around 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 function ExceptionTest: TStringList;begin                          Result := TStringList.Create;  Raise Exception.Create('Test');end; procedure Test;var sl: TStringList;begin  sl := ExceptionTest;  try  finally    sl.Free;  end;end;We get the following heaptrc output: 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 5 memory blocks allocated : 204/2162 memory blocks freed     : 76/803 unfreed memory blocks : 128True heap size : 294912 (2464 used in System startup)True free heap : 291984Should be : 292024Call trace for block $01637830 size 12So the StringList is never freed. So it is up to the function that returns the object to not produce memory leaks when throwing an exception ---------------------------------------------------------------------- marcov · 2022-04-19 16:19 But how is 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     function ExceptionTest: TStringList;    begin                      Raise Exception.Create('Test');            Result := TStringList.Create;    end;         procedure Test;    var sl: TStringList;    begin      sl := ExceptionTest;      try      finally        sl.Free;      end;    end;  any different from 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     function ExceptionTest: TStringList;    begin                      Raise Exception.Create('Test');            Result := TStringList.Create;    end;         procedure Test;    var sl: TStringList;    begin      sl := ExceptionTest;      sl.Free;    end;  ? ---------------------------------------------------------------------- Martin_fr · 2022-04-19 16:38 Quote from: sunjob on April 19, 2022, 05:23:39 pmasked the author: Quoteis it pointless to use the try-finally construct in this way? if something happens in the process of sending a request, then the resource will not be released got the answer: Quoteon the contrary, there will certainly be a liberation If  "// here void" means: "No code in the try-block" or "an empty try- block", then the try finally is indeed pointless. 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 var ResponceStream : TWhateverResponseClass;begin  ResponceStream := PostRequest(UrlCtrl + '/api/hello', PostSource);  try     // here void // no code // empty try-block  finally    ResponceStream.Free;  end;end;  In the above example: - the assignment-code above the "try" is not covered anyway    (Any error in that line, will skip the entire "try finally end" block.) - the empty try finally can not cause an error, so the "ResponceStream.Free" is reached with or without the try finally end block. But even if you move it like this 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 var ResponceStream : TWhateverResponseClass;begin    ResponceStream := nil; // make sure the finally does not get a random non nil value  try    ResponceStream := PostRequest(UrlCtrl + '/api/hello', PostSource);     // no code after assignment  finally    ResponceStream.Free;  end;end;  In this case, if an error happens inside "PostRequest()" then - the assignment to "ResponceStream" has not yet been executed - "ResponceStream.Free" does free an "nil" value. ---------------------------------------------------------------------- Warfley · 2022-04-19 16:39 It isn't, you only need this if there is something done with the stringlist later on. If not, there is no reason to store this value in a variable at all: 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     function ExceptionTest: TStringList;    begin                      Raise Exception.Create('Test');            Result := TStringList.Create;    end;         procedure Test;    begin      ExceptionTest.Free;    end; ---------------------------------------------------------------------- PascalDragon · 2022-04-20 09:13 Quote from: sunjob on April 19, 2022, 05:23:39 pmtry-finally - resource release (fpc/lazarus) good day/night! I read someone else's code, "there is a misunderstanding" 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 beginvar ResponceStream := PostRequest(UrlCtrl + '/api/hello', PostSource);try// here voidfinally  ResponceStream.Free;  end;end;  asked the author: Quoteis it pointless to use the try-finally construct in this way? if something happens in the process of sending a request, then the resource will not be released got the answer: Quoteon the contrary, there will certainly be a liberation explain why? :о) That try … finally block is definitely useless, because if PostRequest raises an exception then ResponseStream.Free will never be executed (and it shouldn't because ResponseStream might not have a valid value anyway), because the try block will never be entered. If PostRequest doesn't raise an exception then ResponseStream.Free will be executed anyway as part of the normal program flow. Depending on the operating system the existance of that try … finally-block might even incur a performance impact (though it would be minuscle to any performance impact due to network communication). Though FPC optimizes away an empty try … finally-block and only leaves the code of the finally, so in essence the code would be as follows anyway: 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 begin  var ResponceStream := PostRequest(UrlCtrl + '/api/hello', PostSource);  ResponceStream.Free;end; ---------------------------------------------------------------------- sunjob · 2022-04-20 18:13 Thank YOU/ALL Very Much for the help!