Call aControl.free inside aControl

After reading this , I would like to know what the problem is with the following code:

procedure TForm1.Button5Click(Sender: TObject); begin Button5.free; end; 
+4
source share
2 answers

Put a breakpoint in this procedure and check the call stack. After you return from the event handler, there is still code from Button5 running and another VCL code that expects Button5 to still be there. If you remove an object from under it, there is a good chance that you will eventually corrupt memory or throw exceptions.

If you want to do this, the correct way is to call PostMessage and send a message to the form, which will ultimately ensure the safe release of the object after the current code has completed.

+5
source

Code is the worst kind of error because it does not detect itself in 99.99% of cases. You release the object (button control), while VCL assumes that the object exists. In fact, it happens that the object’s memory is freed up but not reused, so the above code will work fine, as if the object had not yet been freed, but still this is an error.

The following simple error illustrates the situation:

 type PData = ^TData; TData = record Value: Integer; end; procedure NastyBug; var P: PData; begin New(P); P^.Value:= 2; Dispose(P); // nasty buggy code ShowMessage(IntToStr(P^.Value)); P^.Value:= 22; ShowMessage(IntToStr(P^.Value)); end; 

You can test the above code and it should work as expected, because the remaining memory for P is not reused yet, but the code is a clear error.

+1
source

Source: https://habr.com/ru/post/1345732/


All Articles