Re: Proper pointer cleanup question [message #34652 is a reply to message #34651] |
Tue, 08 April 2003 16:45   |
JD Smith
Messages: 850 Registered: December 1999
|
Senior Member |
|
|
On Mon, 07 Apr 2003 16:01:27 -0700, M. Katz wrote:
> I want to make sure I'm taking all the steps necessary to clean up
> pointers and free memory when I'm done with them. Here's an example.
>
> Suppose I have a pointer to a structure that contains pointers.
>
> a = ptr_new({n:10, p:ptrarr(10)})
>
> So, a is a pointer, and ((*a).p)(i) are pointers as well. When I'm done
> with a and all of it's components, I can do a few things to clean it up,
> but I don't want to do more than what's necessary. Here's a few options.
>
> 1) Just a:
> ptr_free, a
>
> 2) a and all of its dependent pointers: for i=0,n_elements( (*a).p )-1
> do $
> ptr_free, ((*a).p)(i)
> ptr_free, a
>
> 3) Re-assign a to a scalar:
> a = 0
>
> 4) Re-assign *a to a scalar:
> *a = 0
Another option is:
heap_free,a
which will accomplish the same as #2 (avoiding a memory leak), and is
only slightly slower. When you're feeling truly lazy, it's quite a
blessing. You have no flexibility to pick and choose what to parts of
a data structure to free, but often this isn't an issue.
Good luck,
JD
|
|
|