R语言中由C函数分配的内存会发生什么情况 [英] What happens to memory allocated by C functions in R language
问题描述
在我的R包中,实现该函数的C代码为使用分配了一些内存。
这个记忆会发生什么?
它会在R的GC的雷达下工作吗?还是会出现内存泄漏?
如果它在R的垃圾回收下,这个内存是否会被回收?
我在R的服务器进程中分配了巨大的5 GB数据作为服务器运行。
在这里,如果我可以从GC的雷达中分配这些内存是个好主意,就像我们在Java外部分配堆内存一样。
所以基本上,我可以在我的C代码中分配大量内存,而不会影响内存吗?
我打算使用malloc或calloc来分配内存。
在Writing R Extensions中描述得相当清楚 - 一个使用<$ c $的R变体c>访问同一个内存池的calloc() / malloc()
。这样R可以 gc()
这些东西,为什么你需要 PROTECT()
annd UNPROTECT()
。
6.1.2用户控制的内存
另一种形式的内存分配是接口
malloc
,
接口提供R错误处理。该内存一直持续到用户释放
为止,并且是为R
工作区分配的内存之外的内存。
接口函数是
TYPE * Calloc(size_t N,TYPE)
类型* Realloc(ANY * P,size_t N,TYPE)
void free(ANY * P)
类似于
calloc
,realloc
和空闲
。如果分配过程中出现
错误,则由R处理,因此如果这些例程
返回内存已成功分配或释放。空闲
会将指针P设置为NULL
。 (一些但不是所有版本的S做
等)。
用户应该安排
Free
这个内存不再需要时,
包括错误或用户中断。这通常可以通过调用R函数中的on.exit
动作方便地完成大部分
- 请参阅
pwilcox <
不要认为由
Calloc分配的内存
/Realloc
来自与malloc
使用的相同池中的
:特别是不使用
free
或strdup
。
这些入口点需要加前缀如果
STRICT_R_HEADERS
已被定义,则R _
In my R package , the C code which implements the function allocates some memory for usage. What happens to this memory ? Will it be under R's GC's radar or would it be a memory leak ? If its under R's garbage collection , will this memory be reclaimed back ?
I have a huge 5 GB of data to be allocated in R's server process which is running as a server. Here it would be a good idea if i can allocate this memory out of GC's radar like we have outside heap memory allocation in Java. So basically , can i allocate a huge amount of memory in my C code without R not disturbing that memory ?
I am planning to use malloc or calloc to allocate memory.
This is described fairly clearly in "Writing R Extensions" -- one uses R variants of calloc()
/ malloc()
that access the same pool of memory. That way R can gc()
these things, and why you need PROTECT()
annd UNPROTECT()
.
6.1.2 User-controlled memory
The other form of memory allocation is an interface to
malloc
, the interface providing R error handling. This memory lasts until freed by the user and is additional to the memory allocated for the R workspace.The interface functions are
TYPE* Calloc(size_t N, TYPE) TYPE* Realloc(ANY *P, size_t N, TYPE) void Free(ANY *P)
providing analogues of
calloc
,realloc
andfree
. If there is an error during allocation it is handled by R, so if these routines return the memory has been successfully allocated or freed.Free
will set the pointer P toNULL
. (Some but not all versions of S do so.)Users should arrange to
Free
this memory when no longer needed, including on error or user interrupt. This can often be done most conveniently from anon.exit
action in the calling R function - seepwilcox
for an example.Do not assume that memory allocated by
Calloc
/Realloc
comes from the same pool as used bymalloc
: in particular do not usefree
orstrdup
with it.These entry points need to be prefixed by
R_
ifSTRICT_R_HEADERS
has been defined.
这篇关于R语言中由C函数分配的内存会发生什么情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!