0

i'm upgrading from Delphi 2010 to Delphi 10.3.3

if i tried to free an uninitialized object on VCL Project, the application disappear instantly and stay running in the background without showing any error

  • i know the object should be initialized first i'm just trying to show the problem

  • i reinstalled Delphi on another PC without editing any settings and got the same behavior

  • Try Except doesn't help

try this code

procedure TForm1.Button1Click(Sender: TObject);
var
TS:TStringList;
begin
  try
         TS.Free;
  except

  end;
end;
Somebody
  • 703
  • 1
  • 7
  • 23
  • 5
    If you try to run `X.Free` on a random pointer `X`, anything can happen. The observed behaviour is a particular example of "anything". But the next time you run the application, something else might happen. And if you run it on another system, again something else might happen. Only if you are lucky will you get an AV. It all depends on the random pointer value... – Andreas Rejbrand May 23 '20 at 11:36
  • "assigned(TS)" always returning true before the object is been created so how can i check if the object successfully created and need to be freed or not if i set "TS=nil;" before "TS.Create" it makes "assigned(TS)" return false if the object not created but i'm worry it may lead to memory leak – Somebody May 23 '20 at 11:46
  • 1
    10.3 Rio works just like D2010. `Assigned(X)` tests if `X` is non-`nil`. If it is non-`nil`, it had better point to a valid object instance -- always avoid dangling pointers. If `X` is a local variable that is not initialized, `Assigned(X)` can be either `True` or `False`, depending on chance. But in any case, that information is meaningless. You must keep track of your objects yourself. If a constructor doesn't raise an exception, you know the object is constructed. If the constructor raises an exception, it will automatically be freed and you know there is no object. – Andreas Rejbrand May 23 '20 at 11:50
  • The following idiom is 100% safe all the time for a single-use local var: `MyFrog := TFrog.Create; try {use the frog} finally MyFrog.Free; end` – Andreas Rejbrand May 23 '20 at 11:51
  • And if you return an object from a function, you do `Result := TFrog.Create; try {initialize the frog} except Result.Free; raise; end`. Again, that is 100% safe all the time. Basically, what I am trying to say is that one should learn the Object Pascal idioms. – Andreas Rejbrand May 23 '20 at 11:53
  • Thanks Andreas, i got your point , i will make sure that the object is successfully created before trying to free it please post it as an answer – Somebody May 23 '20 at 12:12
  • 1
    Entirely possible that the variable happens to hold a reference to something important, like your form! – David Heffernan May 23 '20 at 13:17

0 Answers0