Memory allocation in D

Oskar Linde oskar.lindeREM at OVEgmail.com
Sat Dec 1 01:12:54 PST 2007


Sean Kelly wrote:

> Only arrays get the +1 byte added to their size during allocations.  If 
> an object occupies 16 bytes then it will end up in a 16 byte bucket. The 
> +1 issue for arrays exists to make the program a bit more forgiving for 
> "past the end" errors.  Interestingly, the ANSI C standard actually 
> requires this behavior in its allocators.  I have yet to decide whether 
> or not this is an artifact of C using terminators to mark the end of a 
> block, since using terminators seems more likely to result in such bugs 
> than the length scheme D employs.

The +1 allocation for arrays is AFAIK there to make sure that it is 
valid to have a pointer point one past the end. You want this to a) 
allow efficient iterators, and b) to allow [$..$] slices.

The problems that would arise if the GC didn't allocate that extra byte are

* appending to a [$..$] slice would in some cases be confused by the gc 
as appending to a [0..0] slice of the following allocated array, and 
thereby corrupting that memory.

* all pointers past the end prevents the consecutive memory area to be 
reclaimed by the GC.

-- 
Oskar



More information about the Digitalmars-d mailing list