Question

From the pickaxe:

You may sometimes need to allocate memory in an extension tha t won’t be used for object storage—perhaps you have a giant bitmap for a Bloom filter, an image, or a whole bunch of little structures that Ruby doesn’t use directly. To work correctly with the garbage collector, you should use the following memory allocation routines. These routines do a little bit more work than the st andard malloc function. For instance, if ALLOC_N determines that it cannot allocate the desired amount of mem ory, it will invoke the garbage collector to try to reclaim some space. It will raise a NoMemError if it can’t or if the requested amount of memory is invalid

But in a given function, I know exactly when release the memory. In this case, should I still using ALLOC_N to alloc the memory?

Is there legitime cases when I should free the memory myself, or it is better always use ALLOC_N and don't care about it?

Was it helpful?

Solution 2

You probably should use ALLOC_N to manage memory allocation dynamically, where your C code needs to store things in independently of object data, and the stored data needs to persist over more than one method call (therefore you cannot be certain that deallocation within specific C functions would be called).

If you are just creating something then throwing it away, all within the context of one complex method call, then you can use plain C approaches for memory management. The C stack is fine for the real basics E.g. just declare int foo[1000]; and you can use that array internally, C will use the stack and clean up as normal - Ruby of course has no access to this data, unless you copy it into something at the end. Don't over-use this though, int foo[1000000]; risks blowing the stack and causing a segfault.

The documentation implies one other reason to use ALLOC_N - you will avoid some out-of-memory situations due to the call to garbage collection. Also, you will get a slightly friendlier Ruby-managed process failure if you really are out of memory (as opposed to whatever your C routine would do).

OTHER TIPS

ALLOC_N doesn't free the memory you allocated. If it fails on the first attempt to allocate you memory it will trigger the GC in an attempt to free up more memory and then try again.

You should still free the memory allocated by ALLOC_N. But use xfree instead of free - this isn't that well described unfortunately in guides such as http://www.ruby-doc.org/docs/ProgrammingRuby/html/ext_ruby.html but you find it used in the Ruby source and the source of other Ruby C Extensions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top