[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Chicken-users] Making stack-allocated Chicken-managed objects from

From: Felix
Subject: Re: [Chicken-users] Making stack-allocated Chicken-managed objects from C
Date: Sat, 10 Mar 2012 12:49:49 +0100 (CET)

> I have been poking into the chicken-bind egg and I'd like to modify it
> slightly for my libraries' (Box2D, Chipmunk) heavy use of structs.
> Chicken-bind will generate helper utils for making C-structs inside
> Chicken. Please take a peek at
> My C-snipped in foreign-primitive that's doing the stack-allocation is
> heavily inspired by
> However, I've been getting feedback about this approach about it not being
> completely safe because it can't guarantee the stack won't overflow. From
> what I can make out of the docs, foreign-primitive automatically does a
> minor GC and we should be safe.

As John already wrote, allocating structs on the stack are very unlikely to
cause an overflow, unless the structs are extremely large. Note that "C_alloc"
gets the number of words as argument, not the number of bytes.

> 2. So let's say that we drop C_alloc for being unsafe. Could C_alloc be
> replaced with C_malloc and at least we'd get the struct/blob automatically
> garbage-collected by Chicken? Or are scheme-objects reserved for
> stack-allocated pointers?

C_malloc ist just an alias for malloc(3), the memory allocated by it
is not GC'd (it is "foreign" to the Scheme runtime system). Otherwise
Scheme objects may live on the stack or on the GC'd heap.

> 3. When C-code returns a new scheme-object, does Chicken treat it like any
> other scheme-object created from within Chicken? (Along with GC and all the
> rest of it)

Yes. If the object is on the stack and remains reachable on the next
(minor) collection, it will be moved into the heap. If it is on the
heap it will be subject to normal GC and move on (major)
collections. If the object is not on the stack or the GC'd heap (when
it is "foreign"), it will simply be ignored by the garbage collector,
but slots containing pointers to stack- or GC'd-heap-allocated data
inside a foreign object will be invalid.

> 4. And just for clarity, is there any difference between
> C_bytes *ab = C_alloc( .. size ..) ;     vs.
> C_bytes ab [ .. size ... ];              ?

No, it is basically the same, depending on the C compiler.

> 5. And finally, how fast is stack-allocation/C_alloc compared to
> heap-allocation/C_malloc? (I'm interested in very small structs here!)

Stack allocation is very fast, because it justs needs to bump a
register. Of course pointers to the allocated memory remain only valid
until the stack is unwound (in the next minor GC).


reply via email to

[Prev in Thread] Current Thread [Next in Thread]