[racket] ffi/unsafe and free
Hey there, Neil!
When racket allocates something, it lives in memory that's
managed by the garbage collector unless you say otherwise. By
contrast, when the C library allocates something, racket's
garbage collector has no clue about it -- that's what (free) is
for.
By default, (malloc) allocates a pointer that's managed by the
garbage collector. So, you're (free)ing it yourself, but the
garbage collector comes along later, notices that you haven't
kept that pointer around, and frees it again.
See the "mode" argument in the malloc documentation:
http://docs.racket-lang.org/foreign/foreign_pointer-funcs.html?q=malloc#(def._((quote._~23~25foreign)._malloc))
There are two ways around this. First, you can:
(malloc _pointer 'raw)
and then be extra careful to (free) it yourself later. Or, you
can just (define x (malloc _pointer)) and let the garbage
collector deal with it, being extra careful that the xmms
libraries don't keep that pointer around after racket's garbage
collector frees it.
This post by Thomas Chust helped me understand:
https://lists.racket-lang.org/users/archive/2011-June/045967.html
(see about halfway down)
3 hours ago, Neil Caldwell wrote:
> Hi
>
> I've just started playing with racket, and decided to start with a
> small (that's what I'm telling myself, anyway) project in the form of
> an xmms2 client. To do this, I'm having to interface with
> libxmmsclient. Long story short, I'm having a problem with free, and
> was hoping to get some advice.
>
> If I put the following code into ptr.rkt:
> ####################################
>
> #lang racket
>
> (require ffi/unsafe)
>
> (free (malloc _pointer))
>
> ####################################
>
> and then run it I get a double free error.
>
> ####################################
>
> $ racket ptr.rkt
> *** glibc detected *** /home/neil/apps/racket-5.2/bin/racket: double
> free or corruption (out): 0xb45d4488 ***
> ======= Backtrace: =========
> /lib/libc.so.6(+0x6b6d1)[0xb76ed6d1]
>
> ####################################
>
> I haven't had much luck googling, unfortunatly (I could be search the
> wrong things)
>
> Is this a problem with racket (v 5.2), my setup (compiled it myself
> with all the default switches), glibc version incompatibility, or am I
> just doing something plain wrong?
>
> Thanks for the help,
>
> Neil
--
Hope that helps,
_mike