[R] Problems with .C - [Ff]ree()?

Thomas Lumley tlumley at u.washington.edu
Tue Jan 15 03:35:48 CET 2002


On Tue, 15 Jan 2002, Mark White wrote:
> It was indeed 1.3.something.  I agree that it sounds like a
> memory leak in my code, but... I just tried compiling the
> following C library routine (based on the arguments of a
> file-reading function that's causing problems):
>
>     void R_test (char **filename, int *dim, Rcomplex *matrix)
>     {
>         double *ptr;
>         ptr = (double*) malloc(sizeof(double) * 25600);
>         free(ptr);
>     }
>
> which, when called like this from within my R function
>
>     .C("R_test",as.character(filename),as.integer(adimi),
>         as.complex(im))
>
> produces a segfault in Rf_duplicate soon after returning for
> the somethingth time.  If I make replace the last argument
> with something like complex(5) - rather smaller than im  - I
> don't get an crash.  Likewise I don't get a crash if I just
> repeatedly call R_test from a simple command-line for(){}.
>
> Is there something horribly wrong with my use of .C above?
>

No.  I tried
-----complete program: bar.c ----
#include <R.h>
#include <stdlib.h>

  void R_test (char **filename, int *dim, Rcomplex *matrix)
    {
        double *ptr;
        ptr = (double *) malloc(sizeof(double) * 25600);
        free(ptr);
    }
-----------------------
then
  R SHLIB bar.c
to compile and then in R
  dyn.load("bar.so")
  repeat({
   print(.C("R_test",as.character("filename"), integer(100000),
    complex(100000))[[1]])
  })

with no problems. (I also tried without <stdlib.h> and without the
unnecessary cast to double * on the malloc, for the sake of variety).

I also tried it with
 .C("R_test", as.character("filename"),as.integer(rpois(10000,10)),
     log(as.complex(rnorm(10000))))[[1]]
in case the values mattered. Still no problems.

I could see this happening if you somehow had two different malloc()s
around, but I can't see how you could.


	-thomas



-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list