我的R有内存泄漏?

Mat*_*olo 10 memory-leaks r rcpp

我在Ubuntu 12.04(精确)64位上使用R 2.15.3.如果我在valgrind中运行R:

R -d"valgrind" - vanilla

然后我使用q()退出程序,我得到以下报告:

==7167== HEAP SUMMARY:
==7167==     in use at exit: 28,239,464 bytes in 12,512 blocks
==7167==   total heap usage: 28,780 allocs, 16,268 frees, 46,316,337 bytes allocated
==7167== 
==7167== LEAK SUMMARY:
==7167==    definitely lost: 120 bytes in 2 blocks
==7167==    indirectly lost: 480 bytes in 20 blocks
==7167==      possibly lost: 0 bytes in 0 blocks
==7167==    still reachable: 28,238,864 bytes in 12,490 blocks
==7167==         suppressed: 0 bytes in 0 blocks
==7167== Rerun with --leak-check=full to see details of leaked memory
==7167== 
==7167== For counts of detected and suppressed errors, rerun with: -v
==7167== Use --track-origins=yes to see where uninitialised values come from
==7167== ERROR SUMMARY: 385 errors from 5 contexts (suppressed: 2 from 2)
Run Code Online (Sandbox Code Playgroud)

最近R经常崩溃,特别是当我通过Rcpp调用C++函数时,这可能是原因吗?谢谢!

Dir*_*tel 10

您可能误读了valgrind输出.最有可能的是,由于R作为一个系统被很好地研究,因此没有(明显的)泄漏.然而,R是一种动态类型语言,当然还有分配."绝对丢失:120字节"本质上是测量错误 - 请参阅valgrind文档.

如果您想查看泄漏,请创建一个,例如,使用如下文件:

library(Rcpp)
cppFunction('int leak(int N) {double *ptr = (double*) malloc(N*sizeof(double)); \
             return 0;}')
leak(10000)
Run Code Online (Sandbox Code Playgroud)

保留记忆,甚至明确地超出R的范围,然后退出.我们得到:

$ R -d "valgrind" -f /tmp/leak.R
[...]
R> leak(10000)
[1] 0
R> 
==4479== 
==4479== HEAP SUMMARY:
==4479==     in use at exit: 35,612,126 bytes in 15,998 blocks
==4479==   total heap usage: 47,607 allocs, 31,609 frees, 176,941,927 bytes allocated
==4479== 
==4479== LEAK SUMMARY:
==4479==    definitely lost: 120 bytes in 2 blocks
==4479==    indirectly lost: 480 bytes in 20 blocks
==4479==      possibly lost: 0 bytes in 0 blocks
==4479==    still reachable: 35,611,526 bytes in 15,976 blocks
==4479==         suppressed: 0 bytes in 0 blocks
==4479== Rerun with --leak-check=full to see details of leaked memory
==4479== 
==4479== For counts of detected and suppressed errors, rerun with: -v
==4479== Use --track-origins=yes to see where uninitialised values come from
==4479== ERROR SUMMARY: 31 errors from 10 contexts (suppressed: 2 from 2)
$ 
Run Code Online (Sandbox Code Playgroud)

现在有更多的泄漏(尽管它仍然没有人们希望的那么容易阅读).如果添加建议的标志,它最终将指向malloc()我们进行的调用.

另外,我在一个早期版本的CRAN软件包中有一个实际泄漏的实例,在我的"带有R的HPC简介"幻灯片组中.如果有泄漏,这会有所帮助.如果没有,就很难看清噪音.

简而言之,如果您编写崩溃代码,则可能是您的代码错误.尝试一个最小的可重复的例子是(好的)标准建议.