[racket] Bytes and GC

From: Matthew Flatt (mflatt at cs.utah.edu)
Date: Sun Jan 26 08:30:46 EST 2014

At Sun, 26 Jan 2014 09:59:17 +0400, Roman Klochkov wrote:
> 
> > (define a #"abcd")
> > (define a0 (cast (cast a _bytes _pointer) _pointer _bytes))
> > (eq? a a0)
> #f
> > (bytes-set! a0 2 33)
> > a
> #"ab!d"
> > (immutable? a)
> #t
> So I have two different objects with the same pointer. Will garbage collector 
> work correct in this situation? 

That should be

 (define a0 (cast (cast a _bytes _gcpointer) _gcpointer _bytes))

Otherwise, between the time that the first `cast` returns and the
second `cast` allocates a byte string, there could be a GC that moves
the byte string's content. If the content moves during that time, the
reference produced by the first `cast` would not get updated, since it
isn't marked as a reference to GCable.

> I mean, it should see two reference to the same object in memory. 
> Or it will try to collect the bytestring when 'a' will become inaccessible?

Since `a` and `a0` both reference the bytes as an GCable address,
things will work fine. Specifically, the GC will retains the bytes as
long as either `a` or `a0` is live.

(Of course, using the FFI to change objects that are supposed to be
immutable can create all sorts of other trouble, but I assume that was
just to illustrate that the two byte-string objects reference the same
bytes.)



Posted on the users mailing list.