From pdalgd at gmail.com  Wed Apr 14 10:10:03 2010
From: pdalgd at gmail.com (peter dalgaard)
Date: Wed, 14 Apr 2010 10:10:03 +0200
Subject: [Rd] Why no race condition when returning UNPROTECT-ed memory
	from C?
In-Reply-To: <j2wd4cf43b61004132250s14a6ee9cmc89be3266eb3e721@mail.gmail.com>
References: <j2wd4cf43b61004132250s14a6ee9cmc89be3266eb3e721@mail.gmail.com>
Message-ID: <CFDC9CCA-8B00-4C13-BB26-4B77F536D862@gmail.com>


On Apr 14, 2010, at 7:50 AM, Dominick Samperi wrote:

> Consider the C (or C++) code called from the .Call interface:
> SEXP foo() {
>  SEXP *p = PROTECT(allocVector(REALSXP, 10));
>  ...
>  UNPROTECT(1);
>  return p;
> }
> 
> Why is there no danger that the allocated memory will be garbage
> collected after the UNPROTECT, but before the return of p?
> 
> I have used code like this for some time and have never had a
> problem, but I'm not sure if/why it is guaranteed to work.

Garbage collection is only triggered by allocation. The hard bit is to remember exactly which programming constructs might allocate something, but in the above, there aren't any. You need to watch out with the unprotected return value, though: fee(foo(), fum()) is a standard bug source if fum() allocates.


-- 
Peter Dalgaard
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Email: pd.mes at cbs.dk  Priv: PDalgd at gmail.com



[Rd] Why no race condition when returning UNPROTECT-ed memory from C?
peter dalgaard