alloca() portability

Rahul Dhesi dhesi%cirrusl at oliveb.ATC.olivetti.com
Wed Nov 21 09:11:58 AEST 1990


     ...allocating local space, as opposed to heap space, when the
     amount of space is not known at compile time---should be something
     directly in the language.

Hmmm...this borders on a false dichotomy.  Since this assumption of
alloca() space vs heap space is implicit in many of the postings I have
seen, let's take a look.

On the one hand, you have stack vs heap, i.e., you're talking about
physical arrangement of memory.  On the other hand, you have (at
run-time) local scope vs global scope, i.e., you're talking about the
lifetime of objects.  The two are related but not mutually exclusive.

Why does a built-in alloca() have to allocate space on the stack (or on
any stack)?  (Let's ignore memory models and Intel CPUs for a moment.)
The requirements for alloca() are:  (a) it allocates space when
invoked, and (b) when the current run-time scope is exited, the
allocated space is recovered for future use.  If Doug Gwyn's
nearly-portable alloca() can use heap space, why shouldn't a compiler
built-in be able to do the same even more effectively?

The key thing that needs to be done is to make sure that all possible
ways of exiting the current scope go through the same place.  Then, at
that place in the code, you can manually deallocate all storage that
was allocated by using alloca() (or malloc()).  Since the compiler can
more easily arrange for all scope exists to trigger the execution of
the deallocation code, alloca() should be a built-in.  OR some other
feature of the language, like atexit() but possibly called atreturn(),
should trigger the execution of user-specified code at scope exit.  An
atreturn() mechanism will lead to confusing and error-prone code,
however, which is why alloca() should be built-in.
--
Rahul Dhesi <dhesi%cirrusl at oliveb.ATC.olivetti.com>
UUCP:  oliveb!cirrusl!dhesi



More information about the Comp.lang.c mailing list