[Rd] malloc/calloc/strdup and R's aequivalents

Dirk Eddelbuettel edd at debian.org
Sun Mar 18 04:08:05 CET 2012

On 18 March 2012 at 03:30, oliver wrote:
| Hello,
| when looking at "Writing R Extensions"
| with mem-allocation in mind, I wondered,
| which functions to use to substitute
| malloc(), calloc(), realloc() and strdup() and free().
| It looked like Calloc() or R_Calloc() might be useful for
| some of my tasks, but when trying to use R_Calloc() for example,
| I got some error messages which I don't see where they are coming from.
| Maybe I just have forgotten to includ ethe right header file?

Maybe, but we can't tell as you didn't post a reproducible example. Here is
one, and I turned verbose on to give you the (default) headers:

R> library(inline)
R> f <- cfunction(signature(), verbose=TRUE, body='
+    double *p = Calloc(5, double);
+    Free(p);
+    return R_NilValue;
+ ')
Compilation argument:
 /usr/lib/R/bin/R CMD SHLIB file25df49ab1ccf.cpp 2> file25df49ab1ccf.cpp.err.txt 
ccache g++-4.6 -I/usr/share/R/include      -fpic  -g0 -O3 -Wall -pipe -Wno-unused -pedantic -c file25df49ab1ccf.cpp -o file25df49ab1ccf.o
g++ -shared -o file25df49ab1ccf.so file25df49ab1ccf.o -L/usr/lib/R/lib -lR
Program source:
  1: #include <R.h>
  2: #include <Rdefines.h>
  3: #include <R_ext/Error.h>
  6: extern "C" {
  7:   SEXP file25df49ab1ccf (  );
  8: }
 10: SEXP file25df49ab1ccf (  ) {
 12:    double *p = Calloc(5, double);
 13:    Free(p);
 14:    return R_NilValue;
 16:   warning("your C program does not return anything!");
 17:   return R_NilValue;
 18: }
R> str(f())


"Outside of a dog, a book is a man's best friend. Inside of a dog, it is too
dark to read." -- Groucho Marx

More information about the R-devel mailing list