Memory allocation in D (noob question)

Oskar Linde oskar.lindeREM at OVEgmail.com
Mon Dec 3 23:47:48 PST 2007


mandel wrote:
> Steven Schveighoffer wrote:
> [..]
>> Now I create the valid array slices:
>>
>> int[] array3 = array1[$..$];
>> int[] array4 = array2[0..0];
>>
>> Note that both of these arrays are bit-for-bit identical (both have 0
>> length and the same ptr value).  Which one points to which piece of
>> memory?  How is the GC to decide which memory gets collected?
> I see the problem.
> The first possible solution that comes to my mind seeing this is to
> make array1[0..0] and array1[$..$] equal.
> array1[$..$] could point to the begin of the array.
> Since the slice length is null, it shouldn't matter - would it?

Appending to a (empty or not) array slice starting at the start of an 
allocated block appends in-place rather than allocate a new array. This 
is the reason

while(x)
   a ~= b;

can be reasonably efficient.

So appending to the [$..$] array would (without padding) mean that you 
corrupt the following array.

The upcoming D2 T[new] (hopefully T[*] :) ) array type will probably 
make that a non-issue though.

> Second thought, why not ignore empty slices at all by telling
> the GC that the pointers doesn't hold any data.

Except for the fact that having an empty slice at the start of an 
allocated block is needed for appending to a preallocated block in 
current D, the reason is that the current GC doesn't have that fine 
grained information. It currently only knows "this block might contain 
pointers" and "this block doesn't contain pointers", and in the former 
case, treats everything properly aligned as potential pointers.

-- 
Oskar



More information about the Digitalmars-d mailing list