delphifreedelphi-10.1-berlintbitmap

Access violation when freeing TBitmap variable -- Bitmap variable still assigned after freeing?


I have this code in a VCL Forms Application:

implementation

{$R *.dfm}

var
  MyBitmap: TBitmap;

procedure TFormMain.FormCreate(Sender: TObject);
begin
  MyBitmap := TBitmap.Create;
end;

procedure TFormMain.FormDestroy(Sender: TObject);
begin
  if Assigned(MyBitmap) then
    MyBitmap.Free;
end;

procedure TFormMain.Button1Click(Sender: TObject);
begin
  if Assigned(MyBitmap) then
    MyBitmap.Free;
end;

When I click the button the second time I get an Access violation in MyBitmap.Free; in the button's click handler. But MyBitmap shouldn't be anymore assigned after the first button click. So why the condition if Assigned(MyBitmap) then does not work on the second button click when it obviously did work on the first button click?

Delphi 10.1 Berlin Update 2


Solution

  • The Assigned function only checks the pointer to be Nil. It doesn't perform a check whether the it's pointing to an existing object or not. You need to set it to Nil after freeing it in order to get the Assigned function work as you expect it. FreeAndNil performs both instructions.