[CExt] malloc vs ALLOC
-
http://www.ruby-doc.org/docs/ProgrammingRuby/html/ext_ruby.html#S4
From that, it appear that Ruby Extension framework provides other methods of allocating memory.
ALLOC_N
,ALLOC
,ALLOCA_N
.@unknownuser said:
You may sometimes need to allocate memory in an extension that won't be used for object storage---perhaps you've got a giant bitmap for a Bloom filter, or an image, or a whole bunch of little structures that Ruby doesn't use directly.
In order 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 standard malloc. For instance, if ALLOC_N determines that it cannot allocate the desired amount of memory, 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.
Is it that it's preferred to use these methods over
malloc
? For what purpose would I use these overmalloc
andfree
?I also found this: http://zed.0xff.me/2010/01/17/you-must-free-memory-you-got-from-alloc-n-and-friends
@unknownuser said:
You MUST free memory you got from ALLOC_N & friends
So from the first link I got the impression that using ALLOC would make the GC take care of the data. But this second seem to indicate otherwise - which makes me wonder more on why I would use it.
I just made a test where I needed to make a dynamic C array to keep some data while doing calculations. I used
malloc
to create it and callfree
before I return. Would that be fine? -
Yes, that would be fine to manage it yourself.
-
ALLOC* are just macros that use xmalloc which is a malloc with a if condition for memory exceeded. (I use ALLOC* with free in my code btw)
-
ALLOC*
are safer than malloc? Better practice? -
safer IMHO. also easier on the eye in the source code.
-
ALLOCA_N
@unknownuser said:
Allocates memory for n objects of c-type on the stack---this memory will be automatically freed when the function that invokes ALLOCA_N returns.
Does that mean one does not need free the memory allocated by this variant? Are there times one can not rely on it?
Advertisement