Dynamic Array Question
Jonathan M Davis
jmdavisProg at gmx.com
Tue Sep 20 11:28:35 PDT 2011
On Tuesday, September 20, 2011 11:06 Dax wrote:
> Hi!
> I'm working on a library written in D.
> After some tests I have discovered that my library leaks memory, those
> leaks are caused by dynamics array that I use in my library.
>
> My question is:
> Should dynamics array be deallocated automatically when a procedure
> returns? There is another way to acomplish this?
>
> Maybe I'm doing something wrong, so, I post the function that causes the
> leak:
>
> public string getWindowText(HWND hWnd)
> {
> int len = GetWindowTextLengthW(hWnd);
> wchar[] t = new wchar[len + 1]; // How to deallocate this?
>
> GetWindowTextW(hWnd, t.ptr, len);
>
> /*
> * I'm converting the wchar[] to char[],
> * the variable 't' should be deallocated
> * because I not need it anymore.
> */
> return to!(string)(t[0..len]);
> }
You don't deallocate dynamic arrays. The GC manages them. The GC manages all
of the memory that you allocate in D with new. If the memory gets freed, it
gets freed during a garbage collection cycle. When the GC runs is non-
deterministic. I believe that it normally only ever gets called when new is
called, and it's only going to run when new is called if it thinks that it
needs to run. The fact that your program doesn't reference a chunk of memory
anymore is irrelevant until a garbage collection cycle runs. That memory won't
be freed until then.
However last I heard, the GC still never released memory to the OS, and if
that's still true, even if the GC collects the memory so that your program can
reuse it, the memory usage of your program will never actually go down. So, if
what you're doing is looking at the memory usage of your program, that may
never go down regardless.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list