[Rd] protect/unprotect howto in C code
tlumley at u.washington.edu
Wed May 17 18:47:12 CEST 2006
On Wed, 17 May 2006, Michael Dondrup wrote:
> Thank you very much, Thomas!
> Thanks to the explanation, I think I could almost track down that bug. May I,
> just for clarification, ask a further bunch of questions (sorry). From what
> you say, did I get it right:
> - 'error in unprotect: stack imbalance' is only a warning, it will not cause
> termination, unless R is running as an embedded process (I'm working with
> RSPerl package in perl here)?
> - Forgetting to unprotect a value is harmless, and will only provoke these
Well, it causes a memory leak, and in the unlikely event that you have
finalizers set on the objects the finalizers won't run. Otherwise, yes.
> - If the protect/unprotect is unbalanced within a function call, R will give
> the warning/error already at the exit of this specific function?
Not quite. The warning comes on return from .Call(). If the function you
.Call calls other C functions you will still only get the warning on
return to R.
> - If that is the case, what if I want to return a pointer to a value from a
> function? Do have to unprotect it anyway, before?
Rule 1 applies to the code that calls your function, too. If you return
(a pointer to) an object that from the point of view of the calling
function is newly created, the calling function has to PROTECT it. In
particular, the return value of .Call will be protected if you store it in
More information about the R-devel