Does the garbage collector R collect the memory allocated in C when using the wrapper R?

I use the R-wrapper for the C code. For small runs everything seemed fine, but this weekend I did longer analyzes and I realized that this was a memory leak problem. I got a message:

The Mac OS X boot disk no longer has free memory for the application, and I had to restart my computer.

I assume that I understand correctly, and I have a memory leak. Knowing how R and C memory management will help me understand where a memory leak is occurring. My question is:

What happens to the memory that was allocated at run time C when the pointers are sent back to R? Is this memory freed by the R garbage collector, or is it really important to make sure you free all memory in C for free?

EDIT

Some memory spaces were allocated to R directly and passed to C. These are variables that return to R after this, and I suspect that the R garbage collector will properly manage this memory. Variables that I suspect might cause a memory leak are temporary variables whose memory is allocated to C with mallocor callocthat do not return to R.

+4
source share
1 answer

R The garbage collector does not automatically call C freeunless you report it.

For example, if you have a C function, let it call a “allocator”, which returns a pointer with the appropriate memory:

varA <- .Call("allocator", 1000)  #Allocate 1000 bytes
doProcess(varA) #...

varA <- .Call("allocator", 1000)  #Allocate 1000 bytes again
 #varA is overwritten, so R is going to try to call the object destructor

, "" . :

varA <- .Call("allocator", 1000)  #Allocate 1000 bytes
#let tell R what to do in the garbage collection process:
reg.finalizer(varA, function(x){
                      .Call("deAllocator", x)
                      })
doProcess(varA) #...

varA <- .Call("allocator", 1000) #Allocate 1000 bytes again
#varA is overwritten, so R is going to call "deAllocator" 

"deAllocator" C, .

+1

All Articles