Which is preferable: Free or FreeAndNil?

What is the basic difference between Free and FreeAndNil?

Is FreeAndNil = Free + Nil?

When should i use Free and when should i use FreeAndNil?

I am not getting these when goggling can someone help me.

Thanks in advance.

when to use object.free and freeandnil(object); [duplicate]

Possible Duplicate: Which is preferable: Free or FreeAndNil? when to use free and freeandnil? in my way, i usually use the .free when the object that created is something like object.create; that

Why should I use Free and not FreeAndNil in a destructor?

I have read A case against FreeAndNil but still don’t understand why I cannot use this method in a class destructor ? Can anyone explain. Update: I think the comment from Eric Grange was most useful f

Which URL rewriting scheme is preferable? Wiki/Blog style?

I’m writing some URL rewriting software, and I want to know which URL scheme is preferable from many points of view: Blog style: my-chemistry-answer — Why? — (not preferable, technical) Wiki style:

What is the alternative to FreeAndNil in Delphi 7?

I have a doubt that whether FreeAndNil is the ideal approach to dispose an object . I have come across codes where something like StringList1.Free; StringList1 := Nil; is used. Is the above line an o

Which is preferable for each, in or for_each?

When using Visual Studio, I can write a container traversal in at least the following three ways. Which way is preferable? Assuming: vector<CString> strings1; Method 1 (using the for_each algor

Which is preferable, a = [] or a = new Array()?

In Actionscript 3, which is preferable? a = [1,2,3]; or a = new Array(1,2,3); It appears that calling the Array constructor with data as individual arguments would be slower and that the other metho

Which is preferable: “const” or “static readonly”? [duplicate]

Possible Duplicate: C#: Static readonly vs const Which is preferable in this instance (no pun intended): const or static readonly? I changed some const declarations to static readonly after eith

Which is preferable and less expensive: class matching vs exception?

Which is less expensive and preferable: put1 or put2? Map<String, Animal> map = new Map<String, Animal>(); void put1(){ for (…..) if (Animal.class.isAssignableFrom(item[i].getClass()) ma

Which is preferable – printf or fprintf

I know that both of the functions can be used to output to the console. I read that question, but no one didn’t tell which is prefered to be used when outputing to the console. So which function is be

For eclipse which -vm is preferable?

I am using eclipse 3.6 while using Virtual Machine, which one is better option. Option1: -vm C:/Program Files/Java/jdk1.6.0_22/bin/javaw.exe Option2: -vm C:/Program Files/Java/jre6/bin/javaw.exe



And have a look at the implementation:

procedure FreeAndNil(var Obj);
  Temp: TObject;
  Temp := TObject(Obj);
  Pointer(Obj) := nil;


Consider the following code:

procedure TForm1.FormCreate(Sender: TObject);
  bm: TBitmap;
  bm := TBitmap.Create;
  bm.LoadFromFile('C:/Users/Andreas Rejbrand/Documents/RAD Studio/6.0/Demos/DelphiWin32/VCLWin32/Football/up.bmp');

  if Assigned(bm) then
    bm.SaveToFile('C:/Users/Andreas Rejbrand/Desktop/test.bmp')
    ShowMessage('Cannot save! The bitmap does no longer exist!');

This will create an error or an invalid (empty) bitmap on my desktop, because I try to use an object that has been freed. Yes, even though bm has been freed, it is still “assigned”, i.e. bm still points to a memory adress, even though there is nothing (usable) there. To overcome this, one can set bm := nil, as a safeguard, Then assigned(bm) will return false, as one would want. More or less, FreeAndNil(bm) is a shorthand for bm.Free; bm := nil. The first statement frees all memory (and OS resources, CPU time etc. used by the object), and bm := nil sets the “pointer” bm to nil, so that bm no longer points to the place where the object used to be, but no longer is. This way you (and routines like assigned) will not get fooled to believe that there still is a bitmap object.


Some say that you should always use FreeAndNil(foo) rather than foo.Free. Well, why not? The additional instruction foo := nil will probably not take too many nanoseconds to execute, and indeed assigned(foo) = false is a very nice property of a freed object. But then again, if you know what you are doing, and know that you will never use the foo object again after freeing it, then you could stick to just foo.free. Really, some would argue that in many cases (but not all), trying to use a variable of a freed object is a bug by itself. (Of course there are cases where you do this intentionally – you have an object foo that sometimes is assigned and sometimes is not.)

@Bharat, the difference between Free and FreeAndNil is that in addition to free memory used by an object FreeAndNil sets the object reference to nil.

you can check theses links for discussions about use Free or FreeAndNil

Basically, FreeAndNil sets the reference to nil and then frees the object. This marks it as unassigned. So the only reason you would need to use FreeAndNil is if your code is going to reuse the reference. If you’re in a destructor or a finally block, freeing objects that you’re never going to touch again, just use Free.

See Delphi Memory Management Made Simple for an example of when I did find it useful. Mghie’s comment at the bottom is also worth reading.

I’ll answer in a different way.

Maybe, filling your object reference with nil after freeing your object is not always a good idea.

That way, you do not have a distinction between a reference that was never used (and hence is nil), and a reference that has been used, but should not be used in the future.

So, filling it with a magic number (similar to what the FastMM memory manager can do with the content of blocks of memory when those blocks are freed).


Even if doesn’t seem to be much different than Free, it will help you a lot later while hunting to bugs your code.

Just think what happens if you DON’T use FreeAndNil and then somewhere in your code you access a freed object. If you are terrible lucky, your program will crash when it runs home (yes that’s crash is a ‘good’ crash). If you are a bit unlucky it will crash in customer’s computer. Then the real pain starts!

As others already pointed, the FreeAndNil itself is not bad. The FreeAndNil function is not broken/obsolete or something like this and it will not corrupt your code. Some will argue that relying on FreeAndNil may lead or indicate a design flaw.

I use FreeAndNil EVEN on a local variable. Using it on a local variable seems POINTLESS since the variable vanishes as soon as you exit the procedure. However, it is good practice that will cost you few extra bytes only. Think that you may at a later date add more code at the end of the procedure, AFTER the point where you freed the object, code that will (obviously accidentally) try to access the freed object. If the object was NIL, BABUM, instant AV (example).
Note: Some people may say they never ever accessed a free object (basically meaning they never make mistakes) so they don’t need FreeAndNil in this case. Well, I am not a robot. I do mistakes.

Some conservative people may say this simple call will waste RAM and CPU resources. I will never ever say that conserving memory/CPU is bad. I like to deliver small/fast/monolithic applications too! But I don’t think that removing using FreeAndNil will waste more than few bytes and CPU cycles (literally few). It will not make a real difference in the day-by-day life, especially when you think that a single graphic resource like a TButton glyph or your program’s icon can take 50-300KB, and your program can have dozens of these.

Mason Wheeler already points to a article that shows the ‘lazy creation’ method that uses FreeAndNil that we all used one day: http://tech.turbu-rpg.com/106/delphi-memory-management-made-simple

Allen Bauer shows here an example about how using the FreeAndNil in the a CERTAIN case (destructor of a visual component) and be indeed bad: http://blogs.embarcadero.com/abauer/2010/02/16/38916
Allen states that FreeAndNil should be replaced with better methods. For example with FastMM. However, here is a simple piece of code where FastMM fails while FreeAndNil saves the day: http://codeverge.com/embarcadero.delphi.rtl/freeandnil-to-use-or-not-to-use/1067733

Since there are both arguments pro and against FreeAndNil, it is up to you to decide if like it or not.