lazy memory allocation

Steve Kargl sgk at troutmask.apl.washington.edu
Sat Aug 24 20:50:37 UTC 2013


On Sat, Aug 24, 2013 at 09:35:53PM +0100, Anton Shterenlikht wrote:
> >From sgk at troutmask.apl.washington.edu Fri Aug 23 19:28:09 2013
> >
> >On Fri, Aug 23, 2013 at 11:25:58AM +0100, Anton Shterenlikht wrote:
> >> I've been burned by what's apparently called
> >> "lazy memory allocation" on linux.
> >> 
> >> My code calls a subroutine that allocates
> >> a coarray. This routine exits fine, with
> >> no error. However, when I tried to initialise
> >> the coarray, I got segfault. On investigation
> >> I discovered that the coarray was not in fact
> >> allocated. In my particular case this was
> >> because there was not enough memory.
> >> 
> >> Anyway, I was later told that this is an
> >> expected behaviour on linux, with its
> >> "lazy memory allocation".
> >> 
> >> I'm wondering if FreeBSD also uses
> >> a lazy memory allocation, or we do it differently?
> >
> >man malloc.
> >
> >FreeBSD uses jemalloc, which allows one to tune the 
> >allocators behavior.  I suspect, but have not tried
> >to verify, that by default it uses lazy memory 
> >allocation.
> >
> >To avoid possible issues with lazy memory allocation,
> >initialize the memory.
> >
> >real, allocatable :: a(:)
> >allocate(a(10) :: source=0.)
> 
> ok, thanks for this hint
> 
> >You can also add in STAT and ERRMSG after SOURCE to 
> >inspect whether allocation was successful.
> 
> That's the thing. I had it, like in
> 
> integer :: errstat=0
> allocate(a(10),stat=errstat)
> if (errstat .ne. 0) stop "some msg"
> 
> And didn't get stopped, i.e. errstat was zero
> on exit from ALLOCATE. The segfault happened on
> 
> a = some_value
> 

Yes, of course, that's the behavior expected with lazy allocation.
The return status from malloc will indicate that memory has been
allocated, but it isn't actaully allocated until its touched.
That's why you need to do 'allocate(a(10) :: source=0.)'.  This
will touch the memory, and should fail on lazy memory allocators
if memory isn't available.

-- 
Steve


More information about the freebsd-fortran mailing list