SmartPascal
FreeAndNil
Procedure
Free memory for an object and set it to nil SysUtils unit
 procedure FreeAndNil ( var ObjectReference ) ;
Description
The FreeAndNil procedure frees up the memory used by an object, and sets the object reference to nil.
 
It actually does this in reverse order - first dereferencing the object before deallocating the memory. This is a very clean way of freeing resources.
Related commands
FreeMem Free memory storage used by a variable
GetMem Get a specified number of storage bytes
Nil A pointer value that is defined as undetermined
Null A variable that has no value
 
Example code : Free and nil an object, and then try to do this again
var
  myList : TList;

begin
  // Create the list object
  myList := TList.Create;

  // And now free and nil this object
  FreeAndNil(myList);

  // We can safely do this twice - it ignores nil objects
  FreeAndNil(myList);
end;
Show full unit code
   No exception occurs - the second FreeAndNil does nothing.