Skip to content

Memory Protection & calling C-fun from C

2 messages · Torsten Hothorn, Brian Ripley

#
Good morning!

The descriptions of memory protection all assume that one
is calling a C-function directly from R. I'm not sure if my
understanding of calling a C-function from another C-function
is correct:

Suppose there are two functions

SEXP bar(SEXP y) {
  SEXP b;
  PROTECT(b = allocVector(...));
     ... computations on b
  UNPROTECT(1);
  return b
}

and

SEXP foo(SEXP x) {
  SEXP a;

  PROTECT(a = bar(x));  /* use bar to do lowlevel computations */
    ... futher computations on a
  UNPROTECT(1);
  return a;
}

Of course,

R> .Call("bar", x)

is safe but is

R> .Call("foo", x)

too? May it happen that the object `b' points to is destroyed before it is
protected by `PROTECT(a = bar(x))'?

I searched for examples of that in R and some packages but did only find
some where `bar' is defined by

   double* bar(double *y)

and the problems do not occur. Anyway, I want to be able to call both
`foo' and `bar' directly from R and C-level (say for the sake of writing
tests in R for the lowlevel functions).

Any clarification is very welcome && Thanks in advance,

Torsten
#
Torsten,

Of course, R itself is a C program so the principles apply to interpreted 
calls too, with your code in bar returning control to do_dotcall in your 
first example.

There can be no R memory allocation between returning from bar and 
assigning to a in foo, and it is memory allocation (and invoked gc's) one 
is protecting against.

Brian
On Fri, 2 Apr 2004, Torsten Hothorn wrote: