2

I've started working with ruby C extensions. I'm having trouble understanding what the GC picks up and what not, and if you can actually manually free 'native' ruby objects (like Ruby arrays/strings) created in some C snippet earlier on.

Lets look at an example illustrating my question, the first function allocates some memory that might, or might not get free'd. The second function manually free's up the memory and what I'm wondering is if that will break things in the long run. See below for some background info on where I intend to use it.

static VALUE test_func(VALUE self)
{
    VALUE ary, str1, str2;

    ary = rb_ary_new();
    rb_ary_push(rb_str_new2("test-blabla"));
    rb_ary_push(rb_str_new2("test2-blabla"));

    return ary;
}

Now I have figured out that if you run this, the GC will free this on program termination, and therefore it knows about its existance and I'm asuming the GC will eventually sweep it when you are running this on code on a daemon (i.e. a background process).

My problem is that the GC doesn't sweep often enough so I was wondering if adding a function like below would hurt (e.g. break the GC or something)

static VALUE test_func_free(VALUE self, VALUE ary)
{
    int i, len = RARRAY_LEN(ary);

    for(i = 0; i < len; i++) {
        rb_str_free(rb_ary_entry(ary, i));
    }

    rb_ary_free(ary);
}

Background info

I'm building a server, but to get an answer for clients I need to fiddle around in C a bit. I plan on returning the answers in strings packed in an array (a request can have multiple answers). But when the request is answered I wanted the memory used by the answer gone, the sooner the better.

Looking forward to read your answers,

~ Michel

Michel Megens
  • 123
  • 2
  • 9
  • Calling `GC.start` doesn't satisfy your need to free up unused objects? – thomthom Oct 16 '15 at 22:38
  • I will definitely try that, thanks. Although the issue is kind-of-solved. I started working with a multi-threaded server now (i.e. each connecting client gets its own thread), and as soon as a thread closes its memory seems to be cleaned up pretty fast. – Michel Megens Oct 20 '15 at 16:31

0 Answers0