March 25, 2021
On Tuesday, 16 March 2021 at 23:49:00 UTC, H. S. Teoh wrote:
> 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];

correction: this should be:

        n *= double.sizeof;
        data = cast(double[])(malloc(n)[0 .. n]);  // i.e. slice n == malloc 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


1 2 3
Next ›   Last »