[comp.sys.sun] Is malloc reentrant

mike@unix.cis.pitt.edu (Mike Elliot) (06/29/90)

Is malloc guaranteed to be reentrant, if not is it reentrant on any
systems?
			Mike Elliot
			{allegra|bellcore|cadre|psuvax1}!pitt!cisunx!mike
			mike@unix.cis.pitt.edu
			mike@pittvms.bitnet

henry@zoo.toronto.edu (07/01/90)

>Is malloc guaranteed to be reentrant, if not is it reentrant on any
>systems?

Nothing in the C library is guaranteed reentrant by any
manufacturer-independent specification, e.g. ANSI C.  I would be very
surprised to see it reentrant on any implementation that hadn't been
written with something like user-level threads in mind (and suitable tools
on hand to aid in writing it).  Malloc inherently relies on global data
structures to remember the state of memory, and nothing that relies on
global variables is reentrant in general.

In the absence of threads or other such primitives for parallelism, the
only way you'd get malloc re-entered would be from a signal handler.
BEWARE:  there is almost nothing you can do safely and portably in a
signal handler.  ANSI C guarantees that you can (a) call signal() for the
same signal, (b) assign a value to a static variable of one very specific
type, and (c) *nothing else*.  1003.1 makes some somewhat stronger
promises, but the ability to call malloc() is not among them.

                                         Henry Spencer at U of Toronto Zoology
                                          henry@zoo.toronto.edu   utzoo!henry

lehners@uniol.uucp (Joerg Lehners) (07/01/90)

In comp.sys.sun you write:
>Is malloc guaranteed to be reentrant, if not is it reentrant on any
>systems?

I think malloc can't be reentrant because it modifies a global resource
(the heap). I cannot imagine an algorithmn that modifies a global resource
without using some kind of locking.  Implementing malloc (and friends
free, realloc, calloc) with a locking mechanismn is useless in single
threaded application: another call to malloc from e.g. a signal handler
would block the whole application, if the signal handler was called when
the process was in the middle of malloc.  Whereas malloc with a locking
mechanism would be sensefull in mutli threaded applications (like the
light weight prcess of SunOS4.x)

  Joerg Lehners

/ UUCP:    lehners@uniol              | Joerg Lehners                  \
|       ...!uunet!unido!uniol!lehners | Fachbereich 10 Informatik ARBI |
| BITNET:  066065 AT DOLUNI1          | Universitaet Oldenburg         |
\ Inhouse: aragorn!joerg              | D-2900 Oldenburg               /