The Crystal Programming Language Forum

Questions about pointers and GC

Hello Community!

I am working on a project that need to deal with pointers, but I have some questions:

  • If I use Pointer.malloc, when the memory will be freed ? I guess it’s when it’s collected by the GC, but Pointer is a Value, so isn’t there a specific behavior for Pointers?

  • What append if I copy the address somewhere into a Int64, and reuse this address by doing .... GC can’t detect this probably?

  • If I want to be sure that the address keep allocated until I freed it myself, have I to use GC.malloc / ?.

  • Ideally, I would like indicate to the GC that the address of the pointer is stored elsewhere into and other variable, and to don’t free this pointer until there are no references on my pointer and my variable.
    GC.register_disappearing_link is what I am looking for?, how can I use this function in this case?

Thanks you for enlighten me !

The GC is conservative. That means that if somewhere within the memory an address value is found, it is assumed to be a reference. This despite the type used. So if an integer or string happens to match an address, that address will not be freed.

There are techniques in bdw-gc, the GC we use, to be more specific and declare that some portions of an allocated structure has no pointers. But we don’t use those.

The only exception is when malloc_atomic is used. That atomic means there are no pointers in the block returned by malloc.

So, I can assume things will no be freed accidentally.

If you want to use malloc/free as in C, you need to use LibC.malloc and But if you want those to interact with the GC I think you might need to register them as roots. But I might be wrong in this last bit.

Thanks you bcardiff.

So the GC is more powerful than I was thinking, great!

However I got some troubles with random sigfaults and memory corruption, those always disappearing when I used GC.disable (So I have think than GC freed some pointers too early). Weirdly, these corruptions are significantly reduced by replacing all occurrence of Pointer.malloc by GC.malloc, but still append sometime.

I will try to reduce my code in order to catch if this is not a bug of the GC or if I am simply writing somewhere out of allocated memory. The weird thing is I never seen these corruptions when the GC is disabled.

Note that Pointer.malloc allocates memory via the GC. The one that does not is LibC.malloc.

Right, thanks you!