Dynamic Array Question

Steven Schveighoffer schveiguy at yahoo.com
Tue Sep 20 11:28:54 PDT 2011


On Tue, 20 Sep 2011 14:06:34 -0400, Dax <dax at mailinator.com> 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?

No, in a GC-enabled language, the GC is responsible for cleaning up the  
memory.

> There is another way to acomplish this?

Yes, you can manually free the memory at your own risk.  Note that in any  
GC-enabled language, more memory is consumed than in a manually-managed  
language.  This is because there is a time period where a memory block is  
unused, but still allocated (i.e. the GC hasn't collected it yet).

D's garbage collector is conservative, which means it may keep some blocks  
in memory even though they are no longer in use.  Also, depending on your  
measurement tools, you may be counting freed memory towards memory usage.   
For example, if a block of memory is deallocated, it's not given back to  
the OS, it simply goes back into a pool to be reallocated again later.

> 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 can deallocate the original array.  The soon-to-be-deprecated method  
(but easiest) is:

delete t;

To avoid having to change your other code, I'd do this:

wchar[] t = ...;
scope(exit) delete t; // add this line to the end of the function (after  
returning)

There is another way, but it's not as easy:

// put this at the top of file
import core.memory;

...

scope(exit) GC.free(t.ptr);

However, this is what will be required when delete is deprecated.

-Steve


More information about the Digitalmars-d-learn mailing list