From tlumley at u.washington.edu  Wed May 17 18:47:12 2006
From: tlumley at u.washington.edu (Thomas Lumley)
Date: Wed, 17 May 2006 09:47:12 -0700 (PDT)
Subject: [Rd] protect/unprotect howto in C code
In-Reply-To: <200605171812.10303.michael.dondrup@cebitec.uni-bielefeld.de>
References: <200605171209.23534.michael.dondrup@cebitec.uni-bielefeld.de>
	<Pine.LNX.4.64.0605170732440.24764@homer24.u.washington.edu>
	<200605171812.10303.michael.dondrup@cebitec.uni-bielefeld.de>
Message-ID: <Pine.LNX.4.64.0605170940580.23107@homer22.u.washington.edu>

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)?

Correct.

> - Forgetting to unprotect a value is harmless, and will only provoke these
> warnings?

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 
a variable.

 	-thomas



[Rd] protect/unprotect howto in C code
Thomas Lumley