www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - How to free memory of an associative array

reply "Mark Isaacson" <turck11 hotmail.com> writes:
How can I free the memory used by an associative array?

I need to be able to reuse the same array, but set it to an empty
state and free up the memory it used previously.

I do not believe that setting the associative array to null is
sufficient to free the memory, as it is possible that someone
still has a reference to an element inside, and so the garbage
collector must be conservative.

Thanks in advance!
Jun 24 2014
parent Jonathan M Davis via Digitalmars-d-learn writes:
 Sent: Tuesday, June 24, 2014 at 11:12 AM
 From: "Mark Isaacson via Digitalmars-d-learn"
<digitalmars-d-learn puremagic.com>
 To: digitalmars-d-learn puremagic.com
 Subject: How to free memory of an associative array

 How can I free the memory used by an associative array?
 
 I need to be able to reuse the same array, but set it to an empty
 state and free up the memory it used previously.
 
 I do not believe that setting the associative array to null is
 sufficient to free the memory, as it is possible that someone
 still has a reference to an element inside, and so the garbage
 collector must be conservative.
On Tue, 24 Jun 2014 18:12:06 +0000 Mark Isaacson via Digitalmars-d-learn <digitalmars-d-learn puremagic.com> wrote:
 How can I free the memory used by an associative array?

 I need to be able to reuse the same array, but set it to an empty
 state and free up the memory it used previously.

 I do not believe that setting the associative array to null is
 sufficient to free the memory, as it is possible that someone
 still has a reference to an element inside, and so the garbage
 collector must be conservative.
Well, if something still has references to its internals, freeing the memory would be a bug in your program. Also, manually freeing GC memory is pretty much always a bad idea. If you really want to do that, use malloc and free (though that would require writing your own AA implementation - the built-in one is designed to manage itself and is not particularly tweakable). Regardless, the memory of the AA is managed entirely by the GC, and I don't believe that there is any way that you can force it to be freed. The best that you can do is make sure that no references to the AA currently exist and then explicitly run a collection. Regardless, if you want to be managing memory, I'd strongly suggest that you not do it with GC-allocated memory. It's just begging for trouble. If you want to use the GC, let it do its job. Anything along the lines of forcibly freeing GC memory will be incredibly bug-prone. - Jonathan M Davis
Jun 24 2014