GC and slices

Sean Kelly sean at f4.ca
Thu Sep 21 08:42:53 PDT 2006


Lionello Lunesu wrote:
> Walter Bright wrote:
>> Oskar Linde wrote:
>>> This is a very short question regarding the liberties of the GC. Is 
>>> it safe to rely on data outside a slice?
>>
>> Yes, because all a slice is is an interior pointer, and interior 
>> pointers hold the entire allocated chunk.
> 
> Are you guys sure?!
> 
> I was using a void[] as a fifo queue, appending new items to the list 
> with ~= and removing processed items with list = list[1..$] and was 
> wondering if the memory at the beginning of the list.ptr was ever being 
> freed, so I made this small test program:
> 
> #import std.stdio;
> #long[] queue = [123,1234,1233,435,7654,54,3241];
> #void main() {
> #    const size_t MASK = 1024*1024*16-1;
> #    size_t size;
> #    while (1) {
> #        queue ~= size;            // anything
> #        size += long.sizeof;
> #        long* t = queue.ptr;
> #        queue = queue[1..$];
> #        assert( queue[0] != 123 );    // popped?
> #        assert( queue.length == 7 );   
> #        assert( (t+1) == queue.ptr );    // moved?
> #        if ((size&MASK) == 0)        // stats
> #            writefln(size);
> #    }
> #}   
> 
> and it seems it IS being freed! The (virtual) memory is not growing!

When you try to append to a slice a reallocation occurs--growing an 
array in place is only possible if your array reference refers to the 
head of the memory block.  Also, a rellocation will occur on an append 
periodically as the as the block grows.  Up to 4096 bytes (the size of a 
memory page) reallocations will occur when the array passes a power of 
two boundary--16, 32, 64, etc--beyond 4096 bytes a reallocation will 
occur when the array passes a page boundary.  This has to do with how 
the GC manages memory, and it is a pretty typical allocator design.


Sean



More information about the Digitalmars-d mailing list