From jbullard at pacificbiosciences.com  Thu Sep 15 19:30:00 2011
From: jbullard at pacificbiosciences.com (James Bullard)
Date: Thu, 15 Sep 2011 17:30:00 +0000
Subject: [Rd] External pointers and an apparent memory leak
In-Reply-To: <D67194B6-A1F2-44B9-9DD1-61139E75DEAC@r-project.org>
References: <7B72273302B0994797DC8CC69E56FD260450FA@DC-EXCHMBX01.Nanofluidics.com>,
	<D67194B6-A1F2-44B9-9DD1-61139E75DEAC@r-project.org>
Message-ID: <7B72273302B0994797DC8CC69E56FD260452FF@DC-EXCHMBX01.Nanofluidics.com>

Hi Simon, Matt

First, thank you for the help. My memory is still growing and it is clear that I'm removing the things I am allocating - potentially it is just Linux not giving back the memory until another process needs it, but it definitely doesn't behave that way when I allocate directly within R. To be a better poster:

#> system("uname -a")
#Linux mp-f020.nanofluidics.com 2.6.32-30-server #59-Ubuntu SMP Tue Mar 1 22:46:09 UTC 2011 x86_64 #GNU/Linux

#> sessionInfo()
#R version 2.13.1 Patched (2011-09-13 r57007)
#Platform: x86_64-unknown-linux-gnu (64-bit)

Here, if you look at the successive allocations you'll see that by the end I have started to grow my memory and, at least w.r.t. the ps method of memory profiling, I'm leaking memory.

> showPS <- function() system(paste('ps -eo pid,vsz,%mem | grep', Sys.getpid()))
> gcl <- function() { lapply(1:10, gc, verbose = F)[[10]] }
> 
> showPS()
18937 147828  0.1
> m <- .Call("h5R_allocate_gig")
> rm(m)
> gcl()
         used (Mb) gc trigger (Mb) max used (Mb)
Ncells 213919 11.5     407500 21.8   213919 11.5
Vcells 168725  1.3     786432  6.0   168725  1.3
> showPS()
18937 147828  0.1
> 
> m <- sapply(1:1000, function(a) {
+   .Call("h5R_allocate_meg")
+ })
> rm(m)
> gcl()
         used (Mb) gc trigger (Mb) max used (Mb)
Ncells 213920 11.5     467875   25   213920 11.5
Vcells 168725  1.3     786432    6   168725  1.3
> showPS()
18937 147828  0.1
> 
> m <- sapply(1:100000, function(a) {
+   .Call("h5R_allocate_k")
+ })
> rm(m)
> gcl()
         used (Mb) gc trigger (Mb) max used (Mb)
Ncells 213920 11.5     818163 43.7   213920 11.5
Vcells 168725  1.3     895968  6.9   168725  1.3
> showPS()
18937 271860  0.9
> 
> m <- sapply(1:1000000, function(a) {
+   .Call("h5R_allocate_k")
+ })
> rm(m)
> gcl()
         used (Mb) gc trigger (Mb) max used (Mb)
Ncells 213920 11.5     785114 42.0   213920 11.5
Vcells 168725  1.3    1582479 12.1   168725  1.3
> showPS()
18937 1409568  7.8

I have redone the examples to better demonstrate the issue I am seeing. Below is the C code:

#include <hdf5.h>
#include <Rinternals.h>    
#include <R.h>
void h5R_allocate_finalizer(SEXP eptr) {
    char* vector = R_ExternalPtrAddr(eptr);
    Free(vector);
    R_ClearExternalPtr(eptr);
}
SEXP h5R_allocate_meg() {
    char* vector = (char*) Calloc(1048576, char);
    for (int j = 0; j < 1048576; j++) {
    	vector[j] = 'c';
    }
    SEXP e_ptr = R_MakeExternalPtr(vector, R_NilValue, R_NilValue); 
    PROTECT(e_ptr);
    R_RegisterCFinalizerEx(e_ptr, h5R_allocate_finalizer, TRUE);
    UNPROTECT(1);
    return e_ptr;
}
SEXP h5R_allocate_k() {
    char* vector = (char*) Calloc(1024, char);
    for (int j = 0; j < 1024; j++) {
    	vector[j] = 'c';
    }
    SEXP e_ptr = R_MakeExternalPtr(vector, R_NilValue, R_NilValue); 
    PROTECT(e_ptr);
    R_RegisterCFinalizerEx(e_ptr, h5R_allocate_finalizer, TRUE);
    UNPROTECT(1);
    return e_ptr;
}
SEXP h5R_allocate_gig() {
    char* vector = (char*) Calloc(1073741824, char);
    for (int j = 0; j < 1073741824; j++) {
    	vector[j] = 'c';
    }
    SEXP e_ptr = R_MakeExternalPtr(vector, R_NilValue, R_NilValue); 
    PROTECT(e_ptr);
    R_RegisterCFinalizerEx(e_ptr, h5R_allocate_finalizer, TRUE);
    UNPROTECT(1);
    return e_ptr;
}


Finally, when I use valgrind on the test script, I see:

==22098== 135,792 bytes in 69 blocks are possibly lost in loss record 1,832 of 1,858
==22098==    at 0x4C274A8: malloc (vg_replace_malloc.c:236)
==22098==    by 0x4F5D799: GetNewPage (memory.c:786)
==22098==    by 0x4F5EE6F: Rf_allocVector (memory.c:2330)
==22098==    by 0x4F6007F: R_MakeWeakRefC (memory.c:1198)
==22098==    by 0xE01BACF: h5R_allocate_k (h5_debug.c:33)
==22098==    by 0x4EE17E4: do_dotcall (dotcode.c:837)
==22098==    by 0x4F18D02: Rf_eval (eval.c:508)
==22098==    by 0x4F1A7FD: do_begin (eval.c:1420)
==22098==    by 0x4F18B1A: Rf_eval (eval.c:482)
==22098==    by 0x4F1B7FC: Rf_applyClosure (eval.c:838)
==22098==    by 0x4F189F7: Rf_eval (eval.c:526)
==22098==    by 0x4E6F3D8: do_lapply (apply.c:72)

Thanks for any help!

jim
________________________________________
From: Simon Urbanek [simon.urbanek at r-project.org]
Sent: Thursday, September 15, 2011 8:35 AM
To: James Bullard
Cc: r-devel at r-project.org
Subject: Re: [Rd] External pointers and an apparent memory leak

Jim,

On Sep 14, 2011, at 5:21 PM, James Bullard wrote:

> I'm using external pointers and seemingly leaking memory. My determination of a memory leak is that the R process continually creeps up in memory as seen by top while the usage as reported by gc() stays flat. I have isolated the C code:
>
> void h5R_allocate_finalizer(SEXP eptr) {
>    Rprintf("Calling the finalizer\n");
>    void* vector = R_ExternalPtrAddr(eptr);
>    free(vector);
>    R_ClearExternalPtr(eptr);
> }
>
> SEXP h5R_allocate(SEXP size) {
>    int i = INTEGER(size)[0];
>    char* vector = (char*) malloc(i*sizeof(char));
>    SEXP e_ptr = R_MakeExternalPtr(vector, R_NilValue, R_NilValue);
>    R_RegisterCFinalizerEx(e_ptr, h5R_allocate_finalizer, TRUE);
>    return e_ptr;
> }
>
>
> If I run an R program like this:
>
> v <- replicate(100000, {
>  .Call("h5R_allocate", as.integer(1000000))
> })
> rm(v)
> gc()
>

This seems a little optimistic to me - at least on the machines most mortals have - since it will allocate ~93GB of memory - before rm/gc:

vmmap:

                                 VIRTUAL ALLOCATION      BYTES
MALLOC ZONE                         SIZE      COUNT  ALLOCATED  % FULL
===========                      =======  =========  =========  ======
DefaultMallocZone_0x1004cf000      62.8M     120044      93.5G    152363%
environ_0x100601000                1024K         27       1280      0%
===========                      =======  =========  =========  ======
TOTAL                              63.8M     120071      93.5G    149977%

ps:

  UID   PID  PPID CPU PRI NI      VSZ    RSS WCHAN  STAT   TT       TIME COMMAND
  501 26287 26170   0  31  0 100511220  64864 -      S+   s002    1:06.81 /Library/Frameworks/R.framework/Resources/bin/exec/x86_64/R

fortunately it's never used, so it's actually possible (purely virtual). But as Matt said, it gets released without problems - after rm/gc:

> gc()
         used (Mb) gc trigger (Mb) max used (Mb)
Ncells 433341 23.2     667722 35.7   597831 32.0
Vcells 630031  4.9    1300721 10.0  1211088  9.3

                                 VIRTUAL ALLOCATION      BYTES
MALLOC ZONE                         SIZE      COUNT  ALLOCATED  % FULL
===========                      =======  =========  =========  ======
DefaultMallocZone_0x1004cf000      59.3M      19083      36.6M     61%
environ_0x100601000                1024K         27       1280      0%
===========                      =======  =========  =========  ======
TOTAL                              60.3M      19110      36.6M     60%

  501 26287 26170   0  31  0  2522872  60880 -      S+   s002    1:35.69 /Library/Frameworks/R.framework/Resources/bin/exec/x86_64/R

> sessionInfo()
R version 2.13.1 (2011-07-08)
Platform: x86_64-apple-darwin9.8.0/x86_64 (64-bit)

locale:
[1] en_US.UTF-8/en_US.UTF-8/C/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base


> Then you can see the problem (top reports that R still has a bunch of memory, but R doesn't think it does). I have tried using valgrind and it says I have memory left on the table at the end lest you think it is because top. Also, I have tried Free/Calloc as well and this doesn't make a difference. Finally, I see this in both R-2-12 (patched) and R-2-13 - I think it is more an understanding issue on my part.
>

You didn't mention your OS - some OSes do not release memory immediately (some wait until you try to allocate new memory) and some can't release certain type of memory at all. Also depending on your OS allocation library you can get more info about the allocation pool to understand what is going on. But for that you'd have to share with us the platform info ...


> thanks much in advance, to me it really resembles the connection.c code, but what am I missing?
>

Cheers,
Simon


PS: This has nothing to do with your question but I'd suggest checking the result on malloc [e.g.,
if (!vector) Rf_error("unable to allocate %d bytes", i);
Also i = asInteger(size) is much more safe (and convenient) than i = INTEGER(size)[0] and completely irrelevantly as.integer(1000000) is more efficiently written as 1000000L.


> thanks, jim
>
>
>       [[alternative HTML version deleted]]
>
> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel
>
>




[Rd] External pointers and an apparent memory leak
James Bullard