Dynamic Array Question

Timon Gehr timon.gehr at gmx.ch
Tue Sep 20 11:32:38 PDT 2011


On 09/20/2011 08:06 PM, 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.
>

Does it 'leak'? What is your exact setup, why isn't the GC collecting 
that memory?

> 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]);
> }
>

Unless the string gets extremely long, you could allocate it on the stack:

wchar[] t=(cast(wchar*)alloca(wchar.sizeof*(len+1)))[0..len+1];





More information about the Digitalmars-d-learn mailing list