From tlumley at u.washington.edu  Thu Dec 30 23:28:49 2004
From: tlumley at u.washington.edu (Thomas Lumley)
Date: Thu Dec 30 23:28:59 2004
Subject: [Rd] optim/vmmin and R_alloc
In-Reply-To: <20041230185913.GA1735@tal.stat.umu.se>
References: <20041230155513.GA22178@tal.stat.umu.se>
	<Pine.A41.4.61b.0412300757350.11816@homer11.u.washington.edu>
	<20041230185913.GA1735@tal.stat.umu.se>
Message-ID: <Pine.A41.4.61b.0412301418350.219480@homer09.u.washington.edu>

On Thu, 30 Dec 2004, [iso-8859-1] Gran Brostrm wrote:

> On Thu, Dec 30, 2004 at 08:01:41AM -0800, Thomas Lumley wrote:
>> On Thu, 30 Dec 2004, [iso-8859-1] Gran Brostrm wrote:
>>>
>>> However, and that is my question/suggestion: Why not use Calloc+Free
>>> instead of R_alloc in vmmin (and maybe in other places)? I made the
>>> changes in 'optim.c' in the functions 'vmmin' and 'Lmatrix'. Then I rebuilt
>>> and reinstalled R-2.0.1. The result was great! My function ran very fast
>>> and
>>> without any memory problems.
>>>
>>> So why not? Or will this change create other problems?
>>
>> Memory will leak permanently if the functions are interrupted or an error
>> occurs.
>
> Not necessarily. If you take a closer look at TFM (as I just did), you find
> in Section 5.1.2:
>
> Users should arrange to  Free  this memory when no longer needed, including
> on error or user interrupt. This can often be done most conveniently from
> an  on.exit  action in the calling  R  function -- see pwilcox for an
> example.

Yes, this could be done.  It would require a second C call (vmfree, say) 
that freed the memory, and would require all uses of vmmin to have an 
on.exit() action that called this vmfree.  Using R_alloc means that nearly 
everyone doesn't have to worry about this, and a few unfortunate people 
have to become experts.

pwilcox has to use Calloc/Free because it is also part of the stand-alone 
math library, which won't have access to the R heap when it is used in 
other applications.


 	-thomas

[Rd] optim/vmmin and R_alloc
Thomas Lumley