Articles   Members Online:
-Article/Tip Search
-News Group Search over 21 Million news group articles.
-Delphi/Pascal
-CBuilder/C++
-C#Builder/C#
-JBuilder/Java
-Kylix
Member Area
-Home
-Account Center
-Top 10 NEW!!
-Submit Article/Tip
-Forums Upgraded!!
-My Articles
-Edit Information
-Login/Logout
-Become a Member
-Why sign up!
-Newsletter
-Chat Online!
-Indexes NEW!!
Employment
-Build your resume
-Find a job
-Post a job
-Resume Search
Contacts
-Contacts
-Feedbacks
-Link to us
-Privacy/Disclaimer
Embarcadero
Visit Embarcadero
Embarcadero Community
JEDI
Links
How to safely Free or FreeAndNil Objects Turn on/off line numbers in source code. Switch to Orginial background IDE or DSP color Comment or reply to this aritlce/tip for discussion. Bookmark this article to my favorite article(s). Print this article
Avoid Dangling Pointers 23-Jul-04
Category
Object Pascal
Language
Delphi All Versions
Views
521
User Rating
No Votes
# Votes
0
Replies
0
Publisher:
Philipp, Steve
Reference URL:
			1   
2   {
3   FreeAndNil(Object) is a good idea, because if you don't nil an object,
4   just free it, and the object stays in scope, you'll get a dangling pointer.
5   Object.Free will only check if the object is nil or not,
6   NOT if it's valid or not!
7   
8   But what do we do if we use a third party component,
9   which may or may not have freed another object???
10  
11  Here is SafeFree: 
12  }
13  
14  procedure SafeFree(var O: TObject);
15  begin
16    try //now do something - ANYTHING that will be caught by try
17         //if the object is invalid
18      O.FieldAddress('7351');
19      //By now we either have a valid object or we went to the except block.
20      FreeAndNil(O);
21    except
22      O := nil;
23    end;
24  end;
25  
26  {
27  In older versions of Delphi, you won't find FreeAndNil, but you can always use this:
28    Object.Free;
29    Object := nil;
30  }
31  
32  Email Address: Support@HeuristicResearch.com


			
Vote: How useful do you find this Article/Tip?
Bad Excellent
1 2 3 4 5 6 7 8 9 10

 

Advertisement
Share this page
Advertisement
Download from Google

Copyright © Mendozi Enterprises LLC