How to delete dynamic array ?

H. S. Teoh hsteoh at quickfur.ath.cx
Tue Mar 16 23:49:00 UTC 2021


On Tue, Mar 16, 2021 at 11:28:00PM +0000, mw via Digitalmars-d-learn wrote:
[...]
> suppose:
> 
>   double[] data;  // D type: dynamic array
> 
> As of 2021 what's the correct way to allocate and deallocate (free
> memory to the system immediately) D's dynamic array?
[...]

Note that T[] is just a slice, not the dynamic array itself. The dynamic
array is allocated and managed by the GC when you append stuff to it, or
when you create a new array with `new` or an array literal.

None of the latter, however, precludes you from using T[] for memory
that you manage yourself. For example, you could do this:

	double[] data;
	data = cast(double[]) malloc(n * double.sizeof)[0 .. n];

Now you have a slice to memory you allocated yourself, and you have to
manage its lifetime manually.  When you're done with it:

	free(data.ptr);
	data = []; // null out dangling pointer, just in case

The GC does not get involved unless you actually allocate from it. As
long as .ptr does not point to GC-managed memory, the GC will not care
about it. (Be aware, though, that the ~ and ~= operators may allocate
from the GC, so you will have to refrain from using them. @nogc may help
in this regard.)


T

-- 
Computers shouldn't beep through the keyhole.


More information about the Digitalmars-d-learn mailing list