alloca, malloc and friends

Richard Tobin richard at aiai.ed.ac.uk
Fri Oct 26 04:55:08 AEST 1990


In article <6793 at suns302.cel.co.uk> ir at cel.co.uk (ian reid) writes:
>The problem is that there is no way that this memory can be returned to the 
>operating system

This is true, at least in most unixes.  Hence it can hardly be a flaw in
malloc() (or rather free()) that it doesn't do it.

Even if sbrk() did allow memory to be returned, it probably wouldn't
be right for malloc() to do it by default.  Most programs (sorry, no
evidence for this claim) don't do one large malloc() and then throw it
away - they either don't free memory at all, or they malloc() and free()
at random times.  Programs of this last type would suffer heavily if
malloc() had to get its memory by a system call each time.

>I'm specualting that alloca(3) which allocates memory on the stack frame was
>invented for two reasons.  Firstly to overcome the above flaw in malloc, and

Alloca() has the same problem.  Stack memory isn't returned to the system
either.

>secondly for speed.

Alloca() will indeed quite possibly be faster - maybe just changing
the stack pointer.  But its main advantage is that you don't need to
free it - it goes away by itself, as if it were a dynamically-sized
local array.

>and as if this weren't enough there is no documented way to grow the stack
>segment so there's less chance of being able to get the memory you want.

Alloca() has this problem to exactly the same extent that local (auto)
variables have it.  In unix, the stack grows automatically when the
process tries to access space beyond the end of it.

-- Richard
-- 
Richard Tobin,                       JANET: R.Tobin at uk.ac.ed             
AI Applications Institute,           ARPA:  R.Tobin%uk.ac.ed at nsfnet-relay.ac.uk
Edinburgh University.                UUCP:  ...!ukc!ed.ac.uk!R.Tobin



More information about the Comp.unix.questions mailing list