Freeing of memory (garbage collection)

Sergey Gromov snake.scaly at gmail.com
Sat Dec 13 02:44:03 PST 2008


Tue, 9 Dec 2008 03:25:07 +0000 (UTC), Dan W wrote:

> 1: Even though D has an automatic garbage collector, is one still
> allowed to free the memory of a malloced array manually (using free
> () ), to avoid pauses in the program?

Just to clarify.  There are 3 types of allocation:

1.  std.c.stdlib.malloc().  The good ol' plain C allocation which is
entirely manual and requires std.c.stdlib.free() to free memory.

2.  std.gc.malloc(), or tango.core.Memory.GC.malloc(), or
core.memory.GC.malloc() in recent D2.  These allocate an uninitialized
but GC-managed and GC-scanned by default memory.  That is, this memory
gets automatically freed as soon as there are no GC-managed references
to it.  You can explicitly free this memory using the delete keyword.
You can direct GC not to scan this memory for pointers using
std.gc.hasNoPointers() or equivalent.

3.  Memory allocated via new, arrays, etc.  This memory is GC-managed
but can be freed explicitly using the delete keyword.

> 2: One justification on the website for using automatic garbage
> collection is how "allocated memory will only be freed if system RAM
> is tight". But surely that's silly, since one may want *lots* of
> memory free for a completely different application (merely memory
> being 'tight' before freeing may not be good enough - one may want D
> to free memory sooner).

I don't think this is a valid justification.  One of the main GC
justifications is an ability to implement flexible data models where
data owner is uncertain or unknown.  In such cases GC makes it easy to
avoid data duplication.


More information about the Digitalmars-d-learn mailing list