Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 143
  • Last Modified:

Free bug?

I had this very strange bug the last day. It's probally easiest if I show you the bug in code.
I have a radiobutton on a form.

formcreate
var
  r: tregistry;
begin
  r.free; //if I don't comment this out rad is destroyed and is nil
  if radiobutton.checked then ...
 
end;
 

is this a bug in delphi ? I thought that a call to free would always be safe even when it's wrong.
0
bnz
Asked:
bnz
1 Solution
 
DragonSlayerCommented:
a safer alternative would be to use

FreeAndNil
0
 
robert_marquardtCommented:
This is wrong code.
A local variable resides on the stack and is NOT initialized to nil.
r.Free only checks for nil and does not call the destructor then. This is a bit of compiler magic.
Since r contains a random value the destructor is called and tries to deallocate data which has never been allocated.
0
 
CrazyOneCommented:
Well I suspect you already now this but before an object can be freed it has to exist first. In this case the object was never created so it can't be freed.

r := TRegistry.Create;


The Crazy One
0

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now