01.11.2011 10:27, breezes пишет:
Thanks Andrej. That bug says that you can not alloc memory during GC. However i
don't alloc but free memory in ~this. But anyway, as you said, I should use
malloc/free in core.stdc.stdlib to manage memory manually. I modified the code 
to
use that malloc/free, and it works without crashing.

However, the following little bit more complex test got a Bus error.

import core.stdc.stdlib;

class Allocator {
        void* alloc(size_t size) {
                return malloc(size);
        }

        void free(void *block) {
                core.stdc.stdlib.free(block);
        }
}

class Pages {
        this(Allocator allocator) {
                _allocator = allocator;
                void *p = _allocator.alloc(1000);
                _pages ~= p;
        }

        ~this() {
                _allocator.free(_pages[0]);// Bus error there
        }

        Allocator       _allocator;
        void*[]         _pages;
        size_t          _a;
        size_t          _b;
        size_t          _c;
        size_t          _d;
        size_t          _e;
        size_t          _f;
}

void main() {
        auto a = new Allocator();
        auto pg = new Pages(a);
}

I got the following bus error:
Bus error: 10

What's the problem? Does it mean that I can not access _allocator during the
deconstruction of pg? And the most mythical thing is that if I comment out the
declaration of _a to _f of Pages, then the bus error will go.

(I use the most recent dmd 2.0.056.)

From http://d-programming-language.org/class.html#destructors
(this page is a bit broken now):

"The garbage collector is not guaranteed to run the destructor for all unreferenced objects. Furthermore, the order in which the garbage collector calls destructors for unreference objects is not specified. This means that *when the garbage collector calls a destructor for an object of a class that has members that are references to garbage collected objects, those references may no longer be valid*. This means that *destructors cannot reference sub objects*. This rule does not apply to auto objects or objects deleted with the DeleteExpression, as the destructor is not being run by the garbage collector, meaning all references are valid."

Make your `free` function static to avoid problem that it needs `this` pointer (of course it may work with damaged `this` but it isn't guaranteed). And your pages array should be allocated with `malloc` too (`~=` allocates in GC heap of course).

Reply via email to